Replace string version of InList method with string_view version since it will work for string as well as string_view.

Add tests.
This commit is contained in:
Neil Hodgson 2025-04-05 14:25:52 +11:00
parent 270863c7b0
commit 78b80c0e53
3 changed files with 42 additions and 3 deletions

View File

@ -191,8 +191,29 @@ bool WordList::InList(const char *s) const noexcept {
/** convenience overload so can easily call with std::string.
*/
bool WordList::InList(const std::string &s) const noexcept {
return InList(s.c_str());
bool WordList::InList(std::string_view sv) const noexcept {
if (!words || sv.empty())
return false;
const char first = sv[0];
const unsigned char firstChar = first;
if (int j = starts[firstChar]; j >= 0) {
const std::string_view after = sv.substr(1);
for (; words[j][0] == first; j++) {
if (std::string_view(words[j] + 1) == after) {
return true;
}
}
}
if (int j = starts[static_cast<unsigned int>('^')]; j >= 0) {
for (; words[j][0] == '^';j++) {
// Use rfind with 0 position to act like C++20 starts_with for C++17
if (sv.rfind(words[j] + 1, 0) == 0) {
return true;
}
}
}
return false;
}
/** similar to InList, but word s can be a substring of keyword.

View File

@ -33,7 +33,7 @@ public:
void Clear() noexcept;
bool Set(const char *s, bool lowerCase=false);
bool InList(const char *s) const noexcept;
bool InList(const std::string &s) const noexcept;
bool InList(std::string_view sv) const noexcept;
bool InListAbbreviated(const char *s, const char marker) const noexcept;
bool InListAbridged(const char *s, const char marker) const noexcept;
const char *WordAt(int n) const noexcept;

View File

@ -44,6 +44,24 @@ TEST_CASE("WordList") {
REQUIRE(!wl.InList(sClass));
}
SECTION("StringViewInList") {
wl.Set("else struct i ^gtk");
std::string_view svStruct = "struct";
REQUIRE(wl.InList(svStruct));
std::string_view svClass = "class";
REQUIRE(!wl.InList(svClass));
// Test single characters
std::string_view svI = "i";
REQUIRE(wl.InList(svI));
std::string_view svA = "a";
REQUIRE(!wl.InList(svA));
// Test prefix
std::string_view svPrefix = "gtk_prefix";
REQUIRE(wl.InList(svPrefix));
}
SECTION("InListUnicode") {
// "cheese" in English
// "kase" ('k', 'a with diaeresis', 's', 'e') in German