]> git.sesse.net Git - plocate/blobdiff - needle.cpp
Proof-of-concept of using ICU for strength-zero searches.
[plocate] / needle.cpp
index 60f169872ac6123c8b06b44477fbe82015b6bb0c..401dbda62005b95564a19deebb71cbc2bb084baa 100644 (file)
 #include <string.h>
 #include <utility>
 
+#include <unicode/coll.h>
+#include <unicode/stsearch.h>
+
 using namespace std;
 
 bool matches(const Needle &needle, const char *haystack)
 {
-       if (needle.type == Needle::STRSTR) {
-               return strstr(haystack, needle.str.c_str()) != nullptr;
-       } else if (needle.type == Needle::GLOB) {
-               int flags = ignore_case ? FNM_CASEFOLD : 0;
-               return fnmatch(needle.str.c_str(), haystack, flags) == 0;
-       } else {
-               assert(needle.type == Needle::REGEX);
-               return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
+       UErrorCode status = U_ZERO_ERROR;
+       icu::UnicodeString target(haystack);  // fromUTF8?
+       icu::UnicodeString pattern(needle.str.c_str());
+       icu::Locale locale = icu::Locale::createCanonical(setlocale(LC_CTYPE, NULL));
+       icu::StringSearch search(pattern, target, locale, nullptr, status);
+       search.getCollator()->setStrength(icu::Collator::PRIMARY);
+       //search.setStrength(icu::Collator::PRIMARY);
+
+       int pos = search.first(status);
+       if (U_FAILURE(status)) {
+               fprintf(stderr, "Could not create a StringSearch object.\n");
+               exit(1);
        }
+       return pos != USEARCH_DONE;
+
+//     if (needle.type == Needle::STRSTR) {
+//             return strstr(haystack, needle.str.c_str()) != nullptr;
+//     } else if (needle.type == Needle::GLOB) {
+//             int flags = ignore_case ? FNM_CASEFOLD : 0;
+//             return fnmatch(needle.str.c_str(), haystack, flags) == 0;
+//     } else {
+//             assert(needle.type == Needle::REGEX);
+//             return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
+//     }
 }
 
 string unescape_glob_to_plain_string(const string &needle)