Skip to content

Commit

Permalink
Add consumePrefix to stringutils
Browse files Browse the repository at this point in the history
  • Loading branch information
wengxt committed Dec 2, 2024
1 parent a85665a commit 0833bbe
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/lib/fcitx-utils/stringutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -407,4 +407,13 @@ std::string escapeForValue(std::string_view str) {

return value;
}

bool consumePrefix(std::string_view &str, std::string_view prefix) {
if (stringutils::startsWith(str, prefix)) {
str = str.substr(prefix.size());
return true;
}
return false;
}

} // namespace fcitx::stringutils
12 changes: 12 additions & 0 deletions src/lib/fcitx-utils/stringutils.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <iterator>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "fcitxutils_export.h"
Expand Down Expand Up @@ -182,6 +183,17 @@ unescapeForValue(std::string_view str);
*/
FCITXUTILS_EXPORT std::string escapeForValue(std::string_view str);

/**
* Return a substring of input str if str starts with given prefix.
*
* \param str input string
* \param prefix to check
* \see startsWith
* \since 5.1.12
*/
FCITXUTILS_EXPORT bool consumePrefix(std::string_view &str,
std::string_view prefix);

} // namespace fcitx::stringutils

#endif // _FCITX_UTILS_STRINGUTILS_H_
8 changes: 8 additions & 0 deletions test/teststringutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ int main() {
FCITX_ASSERT(stringutils::startsWith("abc", "ab"));
FCITX_ASSERT(!stringutils::startsWith("abc", "abd"));
FCITX_ASSERT(!stringutils::startsWith("abc", "abcd"));
FCITX_ASSERT(stringutils::startsWith("abc", ""));
FCITX_ASSERT(!stringutils::endsWith("abc", "ab"));
FCITX_ASSERT(stringutils::endsWith("abc", "abc"));
FCITX_ASSERT(!stringutils::endsWith("abc", "eabc"));
Expand Down Expand Up @@ -128,5 +129,12 @@ int main() {
FCITX_ASSERT(charutils::toHex(i) == i - 10 + 'a');
}
}

std::string_view str = "abc";
FCITX_ASSERT(!stringutils::consumePrefix(str, "ae"));
FCITX_ASSERT(str == "abc");
FCITX_ASSERT(stringutils::consumePrefix(str, "ab"));
FCITX_ASSERT(str == "c");

return 0;
}

0 comments on commit 0833bbe

Please sign in to comment.