summaryrefslogtreecommitdiffstats
path: root/searchlib/src/vespa/searchlib/attribute/string_search_helper.cpp
blob: 1efe39667b812e8f35cd93b23a9653dae64e9691 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "string_search_helper.h"
#include <vespa/searchlib/query/query_term_ucs4.h>
#include <vespa/vespalib/text/lowercase.h>
#include <vespa/vespalib/text/utf8.h>
#include <vespa/vespalib/fuzzy/fuzzy_matcher.h>


namespace search::attribute {

StringSearchHelper::StringSearchHelper(QueryTermUCS4 & term, bool cased, vespalib::FuzzyMatchingAlgorithm fuzzy_matching_algorithm)
    : _regex(),
      _fuzzyMatcher(),
      _term(),
      _termLen(),
      _isPrefix(term.isPrefix()),
      _isRegex(term.isRegex()),
      _isCased(cased),
      _isFuzzy(term.isFuzzy())
{
    if (isRegex()) {
        _regex = (isCased())
                ? vespalib::Regex::from_pattern(term.getTerm(), vespalib::Regex::Options::None)
                : vespalib::Regex::from_pattern(term.getTerm(), vespalib::Regex::Options::IgnoreCase);
    } else if (isFuzzy()) {
        (void) fuzzy_matching_algorithm;
        // TODO: Select implementation based on algorithm.
        _fuzzyMatcher = std::make_unique<vespalib::FuzzyMatcher>(term.getTerm(),
                                                                 term.getFuzzyMaxEditDistance(),
                                                                 term.getFuzzyPrefixLength(),
                                                                 isCased());
    } else if (isCased()) {
        _term = term.getTerm();
        _termLen = strlen(_term);
    } else {
        _ucs4 = term.asUcs4();
    }
}

StringSearchHelper::StringSearchHelper(StringSearchHelper&&) noexcept = default;

StringSearchHelper::~StringSearchHelper() = default;

bool
StringSearchHelper::isMatch(const char *src) const noexcept {
    if (__builtin_expect(isRegex(), false)) {
        return getRegex().valid() && getRegex().partial_match(std::string_view(src));
    }
    if (__builtin_expect(isFuzzy(), false)) {
        return getFuzzyMatcher().isMatch(src);
    }
    if (__builtin_expect(isCased(), false)) {
        int res = strncmp(_term, src, _termLen);
        return (res == 0) && (src[_termLen] == 0 || isPrefix());
    }
    vespalib::Utf8ReaderForZTS u8reader(src);
    uint32_t j = 0;
    uint32_t val;
    for (;; ++j) {
        val = u8reader.getChar();
        val = vespalib::LowerCase::convert(val);
        if (_ucs4[j] == 0 || _ucs4[j] != val) {
            break;
        }
    }
    return (_ucs4[j] == 0 && (val == 0 || isPrefix()));
}

}