19 const auto lead =
static_cast<unsigned char>(text[i]);
20 const int length = lead < 0x80 ? 1 : (lead >> 5) == 0x6 ? 2 : (lead >> 4) == 0xE ? 3 : (lead >> 3) == 0x1E ? 4 : 0;
21 if (length == 0 || i +
size_t(length) > text.size())
26 uint32_t codepoint = length == 1 ? lead : lead & (0x7Fu >> length);
27 for (
int k = 1; k < length; ++k)
29 const auto next =
static_cast<unsigned char>(text[i + size_t(k)]);
30 if ((next & 0xC0u) != 0x80u)
35 codepoint = (codepoint << 6) | (next & 0x3Fu);
38 constexpr uint32_t kLeast[5] = { 0, 0, 0x80, 0x800, 0x10000 };
39 if (codepoint < kLeast[length] || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint > 0x10FFFF)
50 inline void AppendUtf8(std::string& out, uint32_t codepoint)
52 if ((codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint > 0x10FFFF)
54 if (codepoint < 0x80) { out += char(codepoint); }
55 else if (codepoint < 0x800) { out += char(0xC0 | (codepoint >> 6)); out += char(0x80 | (codepoint & 0x3F)); }
56 else if (codepoint < 0x10000) { out += char(0xE0 | (codepoint >> 12)); out += char(0x80 | ((codepoint >> 6) & 0x3F)); out += char(0x80 | (codepoint & 0x3F)); }
57 else { out += char(0xF0 | (codepoint >> 18)); out += char(0x80 | ((codepoint >> 12) & 0x3F)); out += char(0x80 | ((codepoint >> 6) & 0x3F)); out += char(0x80 | (codepoint & 0x3F)); }
std::string ToValidUtf8(std::string_view text)
text with each malformed byte replaced by U+FFFD (the replacement character).
Definition gui_utf8.h:61
void AppendUtf8(std::string &out, uint32_t codepoint)
Appends codepoint as UTF-8; one that isn't a Unicode scalar value (a surrogate, or past U+10FFFF) app...
Definition gui_utf8.h:50
size_t LastUtf8CodepointSize(std::string_view text)
The byte length of text's last codepoint (0 when empty).
Definition gui_utf8.h:78
constexpr uint32_t kInvalidCodepoint
Definition gui_utf8.h:13
uint32_t NextUtf8Codepoint(std::string_view text, size_t &i)
The codepoint starting at text[i], with i moved past it.
Definition gui_utf8.h:17