utf8_safe.h¶
src/facade/utf8_safe.h
@file utf8_safe.h @brief UTF-8-boundary-aware string truncation helper for the facade.
Owners: @tvanfossen
utf8_safe_substr
std::string entropic::facade::utf8_safe_substr(const std::string &s, std::size_t max_bytes)
Truncate a UTF-8 string at-or-before a byte cap on a codepoint boundary.
src/facade/utf8_safe.h:32
Source · 9 lines
inline std::string utf8_safe_substr(const std::string& s, std::size_t max_bytes) {
if (s.size() <= max_bytes) { return s; }
std::size_t cut = max_bytes;
while (cut > 0
&& (static_cast<unsigned char>(s[cut]) & 0xC0) == 0x80) {
--cut;
}
return s.substr(0, cut);
}