Skip to content

Commit

Permalink
feat: add and use utf8subview
Browse files Browse the repository at this point in the history
  • Loading branch information
rept1d committed Dec 19, 2023
1 parent 55a6d20 commit 6443359
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
12 changes: 12 additions & 0 deletions include/dpp/utility.h
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,18 @@ std::string DPP_EXPORT debug_dump(uint8_t* data, size_t length);
*/
size_t DPP_EXPORT utf8len(std::string_view str);

/**
* @brief Return subview of a UTF-8 encoded string in codepoints.
* @note You must ensure that the resulting view is not used after the lifetime of the viewed string has ended.
* @note Result is unspecified for strings that are not valid UTF-8.
*
* @param str string to return substring from
* @param start start codepoint offset
* @param length length in codepoints
* @return std::string_view The requested subview
*/
std::string_view DPP_EXPORT utf8subview(std::string_view str, size_t start, size_t length);

/**
* @brief Return substring of a UTF-8 encoded string in codepoints.
* @note Result is unspecified for strings that are not valid UTF-8.
Expand Down
2 changes: 1 addition & 1 deletion src/dpp/commandhandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ bool commandhandler::string_has_prefix(std::string &str)
{
for (auto& p : prefixes) {
size_t prefix_length = utility::utf8len(p);
if (utility::utf8substr(str, 0, prefix_length) == p) {
if (utility::utf8subview(str, 0, prefix_length) == p) {
str.erase(str.begin(), str.begin() + prefix_length);
return true;
}
Expand Down
8 changes: 6 additions & 2 deletions src/dpp/utility.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ size_t utf8len(std::string_view str) {
return code_points;
}

std::string utf8substr(std::string_view str, size_t start, size_t length) {
std::string_view utf8subview(std::string_view str, size_t start, size_t length) {
/* Shouldn't rely on signedness of char, better cast to unsigned char */
const auto* const s = reinterpret_cast<const unsigned char*>(str.data());

Expand Down Expand Up @@ -537,7 +537,11 @@ std::string utf8substr(std::string_view str, size_t start, size_t length) {
code_points += 1;
}

return std::string(str.substr(subview_start, subview_len));
return str.substr(subview_start, subview_len);
}

std::string utf8substr(std::string_view str, size_t start, size_t length) {
return std::string(utf8subview(str, start, length));
}

std::string read_file(const std::string& filename)
Expand Down

0 comments on commit 6443359

Please sign in to comment.