| 12 | } |
| 13 | |
| 14 | inline size_t utf8_codepoint_count(std::string_view text, std::string_view label) { |
| 15 | size_t count = 0; |
| 16 | for (size_t pos = 0; pos < text.size();) { |
| 17 | const auto ch = static_cast<unsigned char>(text[pos]); |
| 18 | size_t width = 0; |
| 19 | if (ch <= 0x7FU) { |
| 20 | width = 1; |
| 21 | } else if ((ch & 0xE0U) == 0xC0U) { |
| 22 | width = 2; |
| 23 | } else if ((ch & 0xF0U) == 0xE0U) { |
| 24 | width = 3; |
| 25 | } else if ((ch & 0xF8U) == 0xF0U) { |
| 26 | width = 4; |
| 27 | } else { |
| 28 | throw std::runtime_error(std::string(label) + " contains invalid UTF-8"); |
| 29 | } |
| 30 | if (pos + width > text.size()) { |
| 31 | throw std::runtime_error(std::string(label) + " contains truncated UTF-8"); |
| 32 | } |
| 33 | for (size_t i = 1; i < width; ++i) { |
| 34 | if (!is_utf8_continuation(static_cast<unsigned char>(text[pos + i]))) { |
| 35 | throw std::runtime_error(std::string(label) + " contains invalid UTF-8 continuation byte"); |
| 36 | } |
| 37 | } |
| 38 | pos += width; |
| 39 | ++count; |
| 40 | } |
| 41 | return count; |
| 42 | } |
| 43 | |
| 44 | } // namespace engine::text |
no test coverage detected