12#include "../safeguards.h"
19[[nodiscard]] std::pair<char[4], size_t>
EncodeUtf8(
char32_t c)
21 std::pair<char[4], size_t> result{};
22 auto &[buf, len] = result;
25 }
else if (c < 0x800) {
26 buf[len++] = 0xC0 +
GB(c, 6, 5);
27 buf[len++] = 0x80 +
GB(c, 0, 6);
28 }
else if (c < 0x10000) {
29 buf[len++] = 0xE0 +
GB(c, 12, 4);
30 buf[len++] = 0x80 +
GB(c, 6, 6);
31 buf[len++] = 0x80 +
GB(c, 0, 6);
32 }
else if (c < 0x110000) {
33 buf[len++] = 0xF0 +
GB(c, 18, 3);
34 buf[len++] = 0x80 +
GB(c, 12, 6);
35 buf[len++] = 0x80 +
GB(c, 6, 6);
36 buf[len++] = 0x80 +
GB(c, 0, 6);
46[[nodiscard]] std::pair<size_t, char32_t>
DecodeUtf8(std::string_view buf)
48 if (buf.size() >= 1 && !
HasBit(buf[0], 7)) {
52 }
else if (buf.size() >= 2 &&
GB(buf[0], 5, 3) == 6) {
53 if (IsUtf8Part(buf[1])) {
55 char32_t c =
GB(buf[0], 0, 5) << 6 |
GB(buf[1], 0, 6);
56 if (c >= 0x80)
return {2, c};
58 }
else if (buf.size() >= 3 &&
GB(buf[0], 4, 4) == 14) {
59 if (IsUtf8Part(buf[1]) && IsUtf8Part(buf[2])) {
61 char32_t c =
GB(buf[0], 0, 4) << 12 |
GB(buf[1], 0, 6) << 6 |
GB(buf[2], 0, 6);
62 if (c >= 0x800)
return {3, c};
64 }
else if (buf.size() >= 4 &&
GB(buf[0], 3, 5) == 30) {
65 if (IsUtf8Part(buf[1]) && IsUtf8Part(buf[2]) && IsUtf8Part(buf[3])) {
67 char32_t c =
GB(buf[0], 0, 3) << 18 |
GB(buf[1], 0, 6) << 12 |
GB(buf[2], 0, 6) << 6 |
GB(buf[3], 0, 6);
68 if (c >= 0x10000 && c <= 0x10FFFF)
return {4, c};
83 assert(offset <= this->src.size());
84 if (offset >= this->src.size())
return this->end();
87 auto it =
iterator(this->src, offset + 1);
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Bidirectional input iterator over codepoints.
iterator GetIterAtByte(size_t offset) const
Create iterator pointing at codepoint, which occupies the byte position "offset".
std::pair< size_t, char32_t > DecodeUtf8(std::string_view buf)
Decode a character from UTF-8.
std::pair< char[4], size_t > EncodeUtf8(char32_t c)
Encode a character to UTF-8.
Handling of UTF-8 encoded data.