ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
Utf8.hpp
Go to the documentation of this file.
1#pragma once
2
12
13#include <cstddef>
14#include <cstdint>
15#include <string>
16#include <string_view>
17#include <vector>
18#include <algorithm>
19
20namespace ZenitUI::Utf8
21{
25
27 inline constexpr bool isContinuation(unsigned char b) noexcept
28 {
29 return (b & 0xC0u) == 0x80u;
30 }
31
33 inline constexpr bool isValidCodepoint(uint32_t cp) noexcept
34 {
35 return cp <= 0x10FFFFu && !(cp >= 0xD800u && cp <= 0xDFFFu);
36 }
37
43 inline constexpr size_t seqLenFromLead(unsigned char b) noexcept
44 {
45 if (b < 0x80u)
46 return 1;
47 if ((b & 0xE0u) == 0xC0u)
48 return 2;
49 if ((b & 0xF0u) == 0xE0u)
50 return 3;
51 if ((b & 0xF8u) == 0xF0u)
52 return 4;
53 return 1;
54 }
55
60 inline size_t encode(uint32_t cp, std::string &out)
61 {
62 if (!isValidCodepoint(cp))
63 return 0;
64 if (cp <= 0x7Fu)
65 {
66 out.push_back(static_cast<char>(cp));
67 return 1;
68 }
69 if (cp <= 0x7FFu)
70 {
71 out.push_back(static_cast<char>(0xC0u | (cp >> 6)));
72 out.push_back(static_cast<char>(0x80u | (cp & 0x3Fu)));
73 return 2;
74 }
75 if (cp <= 0xFFFFu)
76 {
77 out.push_back(static_cast<char>(0xE0u | (cp >> 12)));
78 out.push_back(static_cast<char>(0x80u | ((cp >> 6) & 0x3Fu)));
79 out.push_back(static_cast<char>(0x80u | (cp & 0x3Fu)));
80 return 3;
81 }
82 out.push_back(static_cast<char>(0xF0u | (cp >> 18)));
83 out.push_back(static_cast<char>(0x80u | ((cp >> 12) & 0x3Fu)));
84 out.push_back(static_cast<char>(0x80u | ((cp >> 6) & 0x3Fu)));
85 out.push_back(static_cast<char>(0x80u | (cp & 0x3Fu)));
86 return 4;
87 }
88
90 inline std::string encode(uint32_t cp)
91 {
92 std::string out;
93 encode(cp, out);
94 return out;
95 }
96
108 inline size_t decode(std::string_view s, size_t pos, uint32_t &outCp) noexcept
109 {
110 if (pos >= s.size())
111 {
112 outCp = 0;
113 return s.size();
114 }
115
116 const unsigned char b0 = static_cast<unsigned char>(s[pos]);
117 if (b0 < 0x80u)
118 {
119 outCp = b0;
120 return pos + 1;
121 }
122
123 if ((b0 & 0xE0u) == 0xC0u && pos + 1 < s.size())
124 {
125 const unsigned char b1 = static_cast<unsigned char>(s[pos + 1]);
126 if (isContinuation(b1))
127 {
128 uint32_t cp = ((b0 & 0x1Fu) << 6) | (b1 & 0x3Fu);
129 if (cp >= 0x80u)
130 {
131 outCp = cp;
132 return pos + 2;
133 }
134 }
135 }
136 else if ((b0 & 0xF0u) == 0xE0u && pos + 2 < s.size())
137 {
138 const unsigned char b1 = static_cast<unsigned char>(s[pos + 1]);
139 const unsigned char b2 = static_cast<unsigned char>(s[pos + 2]);
140 if (isContinuation(b1) && isContinuation(b2))
141 {
142 uint32_t cp = ((b0 & 0x0Fu) << 12) | ((b1 & 0x3Fu) << 6) | (b2 & 0x3Fu);
143 if (cp >= 0x800u && isValidCodepoint(cp))
144 {
145 outCp = cp;
146 return pos + 3;
147 }
148 }
149 }
150 else if ((b0 & 0xF8u) == 0xF0u && pos + 3 < s.size())
151 {
152 const unsigned char b1 = static_cast<unsigned char>(s[pos + 1]);
153 const unsigned char b2 = static_cast<unsigned char>(s[pos + 2]);
154 const unsigned char b3 = static_cast<unsigned char>(s[pos + 3]);
155 if (isContinuation(b1) && isContinuation(b2) && isContinuation(b3))
156 {
157 uint32_t cp = ((b0 & 0x07u) << 18) | ((b1 & 0x3Fu) << 12) |
158 ((b2 & 0x3Fu) << 6) | (b3 & 0x3Fu);
159 if (cp >= 0x10000u && isValidCodepoint(cp))
160 {
161 outCp = cp;
162 return pos + 4;
163 }
164 }
165 }
166
167 outCp = 0xFFFDu;
168 return pos + 1;
169 }
170
175 inline uint32_t next(std::string_view s, size_t &pos) noexcept
176 {
177 uint32_t cp = 0;
178 pos = decode(s, pos, cp);
179 return cp;
180 }
181
183 inline size_t snapFloor(std::string_view s, size_t pos) noexcept
184 {
185 if (pos >= s.size())
186 return s.size();
187 while (pos > 0 && isContinuation(static_cast<unsigned char>(s[pos])))
188 --pos;
189 return pos;
190 }
191
193 inline size_t snapCeil(std::string_view s, size_t pos) noexcept
194 {
195 if (pos >= s.size())
196 return s.size();
197 while (pos < s.size() && isContinuation(static_cast<unsigned char>(s[pos])))
198 ++pos;
199 return pos;
200 }
201
203 inline size_t nextCodepoint(std::string_view s, size_t pos) noexcept
204 {
205 if (pos >= s.size())
206 return s.size();
207 uint32_t cp = 0;
208 return decode(s, pos, cp);
209 }
210
212 inline size_t prevCodepoint(std::string_view s, size_t pos) noexcept
213 {
214 if (pos == 0)
215 return 0;
216 if (pos > s.size())
217 pos = s.size();
218 --pos;
219 while (pos > 0 && isContinuation(static_cast<unsigned char>(s[pos])))
220 --pos;
221 return pos;
222 }
223
225 inline size_t codepointCount(std::string_view s) noexcept
226 {
227 size_t count = 0;
228 size_t pos = 0;
229 while (pos < s.size())
230 {
231 pos = nextCodepoint(s, pos);
232 ++count;
233 }
234 return count;
235 }
236
243 inline constexpr bool isClusterExtend(uint32_t cp) noexcept
244 {
245 return (cp >= 0x0300u && cp <= 0x036Fu) || // Combining Diacritical Marks
246 (cp >= 0x1AB0u && cp <= 0x1AFFu) || // Combining Diacritical Marks Extended
247 (cp >= 0x1DC0u && cp <= 0x1DFFu) || // Combining Diacritical Marks Supplement
248 (cp >= 0x20D0u && cp <= 0x20FFu) || // Combining Marks for Symbols
249 (cp >= 0xFE00u && cp <= 0xFE0Fu) || // Variation Selectors
250 (cp >= 0xFE20u && cp <= 0xFE2Fu) || // Combining Half Marks
251 (cp >= 0x1F3FBu && cp <= 0x1F3FFu) || // Emoji skin-tone modifiers
252 (cp >= 0xE0100u && cp <= 0xE01EFu); // Variation Selectors Supplement
253 }
254
256 inline constexpr bool isRegionalIndicator(uint32_t cp) noexcept
257 {
258 return cp >= 0x1F1E6u && cp <= 0x1F1FFu;
259 }
260
268 inline size_t nextCluster(std::string_view s, size_t pos) noexcept
269 {
270 if (pos >= s.size())
271 return s.size();
272
273 pos = snapFloor(s, pos);
274 uint32_t firstCp = 0;
275 size_t cur = decode(s, pos, firstCp);
276
277 // CRLF counts as a single cluster.
278 if (firstCp == '\r' && cur < s.size() && s[cur] == '\n')
279 return cur + 1;
280
281 // Regional Indicator pair (e.g. flag emojis).
282 if (isRegionalIndicator(firstCp) && cur < s.size())
283 {
284 uint32_t nextCp = 0;
285 size_t nextPos = decode(s, cur, nextCp);
286 if (isRegionalIndicator(nextCp))
287 cur = nextPos;
288 }
289
290 // Consume trailing combining marks, variation selectors, modifiers, and ZWJ chains.
291 while (cur < s.size())
292 {
293 uint32_t cp = 0;
294 size_t after = decode(s, cur, cp);
295 if (isClusterExtend(cp))
296 {
297 cur = after;
298 continue;
299 }
300 if (cp == 0x200Du && after < s.size()) // Zero-Width Joiner
301 {
302 uint32_t joinedCp = 0;
303 size_t afterJoined = decode(s, after, joinedCp);
304 cur = afterJoined;
305 continue;
306 }
307 break;
308 }
309 return cur;
310 }
311
318 inline size_t prevCluster(std::string_view s, size_t pos) noexcept
319 {
320 if (pos == 0)
321 return 0;
322 if (pos > s.size())
323 pos = s.size();
324
325 // If pos was mid-codepoint, snapping down already reaches a valid start < pos.
326 if (pos < s.size() && isContinuation(static_cast<unsigned char>(s[pos])))
327 return snapFloor(s, pos);
328
329 size_t cur = prevCodepoint(s, pos);
330 uint32_t cp = 0;
331 decode(s, cur, cp);
332
333 // CRLF as a single cluster.
334 if (cp == '\n' && cur > 0 && s[cur - 1] == '\r')
335 return cur - 1;
336
337 // Step back over any trailing extenders or ZWJ sequences.
338 while (cur > 0)
339 {
340 if (isClusterExtend(cp))
341 {
342 cur = prevCodepoint(s, cur);
343 decode(s, cur, cp);
344 continue;
345 }
346
347 // If immediately preceded by a ZWJ, step back over ZWJ + previous base.
348 size_t before = prevCodepoint(s, cur);
349 uint32_t beforeCp = 0;
350 decode(s, before, beforeCp);
351 if (beforeCp == 0x200Du && before > 0)
352 {
353 cur = prevCodepoint(s, before);
354 decode(s, cur, cp);
355 continue;
356 }
357 break;
358 }
359
360 // Regional Indicator pair: pair from the start of a consecutive RI run.
361 if (isRegionalIndicator(cp) && cur > 0)
362 {
363 size_t runCount = 0;
364 size_t scan = cur;
365 while (scan > 0)
366 {
367 size_t p = prevCodepoint(s, scan);
368 uint32_t pcp = 0;
369 decode(s, p, pcp);
370 if (!isRegionalIndicator(pcp))
371 break;
372 ++runCount;
373 scan = p;
374 }
375 if ((runCount % 2u) == 1u)
376 cur = prevCodepoint(s, cur);
377 }
378
379 return cur;
380 }
381
389 inline std::vector<size_t> clusterBoundaries(std::string_view s)
390 {
391 std::vector<size_t> bounds;
392 bounds.reserve(s.size() + 1);
393 bounds.push_back(0);
394 size_t pos = 0;
395 while (pos < s.size())
396 {
397 pos = nextCluster(s, pos);
398 bounds.push_back(pos);
399 }
400 return bounds;
401 }
402
409 inline constexpr bool isPrintable(uint32_t cp) noexcept
410 {
411 if (!isValidCodepoint(cp))
412 return false;
413 if (cp < 0x20u || (cp >= 0x7Fu && cp <= 0x9Fu))
414 return false;
415 return true;
416 }
417
424 inline constexpr bool isWordChar(uint32_t cp) noexcept
425 {
426 if ((cp >= 'a' && cp <= 'z') || (cp >= 'A' && cp <= 'Z') ||
427 (cp >= '0' && cp <= '9') || cp == '_')
428 return true;
429 if (cp >= 0x00C0u && cp <= 0x00FFu)
430 return cp != 0x00D7u && cp != 0x00F7u; // exclude × and ÷
431 if (cp >= 0x0100u && cp <= 0x024Fu)
432 return true; // Latin Extended-A/B
433 if (isClusterExtend(cp))
434 return true;
435 if ((cp >= 0x0370u && cp <= 0x052Fu) || // Greek, Cyrillic
436 (cp >= 0x3040u && cp <= 0x30FFu) || // Hiragana, Katakana
437 (cp >= 0x4E00u && cp <= 0x9FFFu) || // CJK Unified Ideographs
438 (cp >= 0xAC00u && cp <= 0xD7AFu)) // Hangul Syllables
439 return true;
440 return false;
441 }
442
444 inline size_t prevWordBoundary(std::string_view s, size_t pos) noexcept
445 {
446 pos = snapFloor(s, pos);
447 while (pos > 0)
448 {
449 size_t p = prevCluster(s, pos);
450 uint32_t cp = 0;
451 decode(s, p, cp);
452 if (isWordChar(cp))
453 break;
454 pos = p;
455 }
456 while (pos > 0)
457 {
458 size_t p = prevCluster(s, pos);
459 uint32_t cp = 0;
460 decode(s, p, cp);
461 if (!isWordChar(cp))
462 break;
463 pos = p;
464 }
465 return pos;
466 }
467
469 inline size_t nextWordBoundary(std::string_view s, size_t pos) noexcept
470 {
471 pos = snapFloor(s, pos);
472 while (pos < s.size())
473 {
474 uint32_t cp = 0;
475 decode(s, pos, cp);
476 if (!isWordChar(cp))
477 break;
478 pos = nextCluster(s, pos);
479 }
480 while (pos < s.size())
481 {
482 uint32_t cp = 0;
483 decode(s, pos, cp);
484 if (isWordChar(cp))
485 break;
486 pos = nextCluster(s, pos);
487 }
488 return pos;
489 }
490
497 inline std::string sanitizeSingleLine(std::string_view src)
498 {
499 std::string out;
500 out.reserve(src.size());
501 size_t pos = 0;
502 while (pos < src.size())
503 {
504 uint32_t cp = 0;
505 size_t next = decode(src, pos, cp);
506 if (cp != 0xFFFDu && isPrintable(cp))
507 encode(cp, out);
508 pos = next;
509 }
510 return out;
511 }
512
519 inline std::string sanitizeMultiLine(std::string_view src)
520 {
521 std::string out;
522 out.reserve(src.size());
523 size_t pos = 0;
524 while (pos < src.size())
525 {
526 if (src[pos] == '\r')
527 {
528 if (pos + 1 < src.size() && src[pos + 1] == '\n')
529 pos += 2;
530 else
531 pos += 1;
532 out.push_back('\n');
533 continue;
534 }
535 if (src[pos] == '\n')
536 {
537 out.push_back('\n');
538 ++pos;
539 continue;
540 }
541 uint32_t cp = 0;
542 size_t next = decode(src, pos, cp);
543 if (cp != 0xFFFDu && isPrintable(cp))
544 encode(cp, out);
545 pos = next;
546 }
547 return out;
548 }
549
550} // namespace ZenitUI::Utf8
551
552namespace ZenitUI
553{
554
565 class CodepointSet
566 {
567 public:
568 CodepointSet() = default;
569
571 CodepointSet &addCodepoint(uint32_t cp)
572 {
574 cps_.push_back(static_cast<int>(cp));
575 return *this;
576 }
577
579 CodepointSet &addRange(uint32_t first, uint32_t last)
580 {
581 if (first > last)
582 return *this;
583 if (last > 0x10FFFFu)
584 last = 0x10FFFFu;
585 cps_.reserve(cps_.size() + static_cast<size_t>(last - first + 1));
586 for (uint32_t cp = first; cp <= last; ++cp)
587 {
589 cps_.push_back(static_cast<int>(cp));
590 }
591 return *this;
592 }
593
600 CodepointSet &addFromUtf8(std::string_view text)
601 {
602 size_t pos = 0;
603 while (pos < text.size())
604 {
605 uint32_t cp = 0;
606 size_t next = Utf8::decode(text, pos, cp);
607 if (cp != 0xFFFDu && Utf8::isPrintable(cp))
608 cps_.push_back(static_cast<int>(cp));
609 pos = next;
610 }
611 return *this;
612 }
613
615 CodepointSet &merge(const CodepointSet &other)
616 {
617 cps_.insert(cps_.end(), other.cps_.begin(), other.cps_.end());
618 return *this;
619 }
620
622 void clear() { cps_.clear(); }
623
625 bool empty() const { return cps_.empty(); }
626
628 std::vector<int> build() const
629 {
630 std::vector<int> out = cps_;
631 std::sort(out.begin(), out.end());
632 out.erase(std::unique(out.begin(), out.end()), out.end());
633 return out;
634 }
635
636 // ---- Presets ----
637
639 static CodepointSet ascii()
640 {
641 CodepointSet s;
642 s.addRange(0x0020u, 0x007Eu);
643 return s;
644 }
645
647 static CodepointSet latin1()
648 {
649 CodepointSet s;
650 s.addRange(0x00A0u, 0x00FFu);
651 return s;
652 }
653
655 static CodepointSet latinExtendedA()
656 {
657 CodepointSet s;
658 s.addRange(0x0100u, 0x017Fu);
659 return s;
660 }
661
663 static CodepointSet typography()
664 {
665 CodepointSet s;
666 for (uint32_t cp : {0x2013u, 0x2014u, 0x2018u, 0x2019u, 0x201Cu,
667 0x201Du, 0x2022u, 0x2026u, 0x20ACu, 0x2122u})
668 s.addCodepoint(cp);
669 return s;
670 }
671
673 static CodepointSet defaultLatin()
674 {
675 return ascii()
676 .merge(latin1())
677 .addCodepoint(0x0152u)
678 .addCodepoint(0x0153u)
679 .merge(typography());
680 }
681
683 static CodepointSet greek()
684 {
685 CodepointSet s;
686 s.addRange(0x0370u, 0x03FFu);
687 return s;
688 }
689
691 static CodepointSet cyrillic()
692 {
693 CodepointSet s;
694 s.addRange(0x0400u, 0x04FFu);
695 return s;
696 }
697
699 static CodepointSet symbols()
700 {
701 CodepointSet s;
702 s.addRange(0x2190u, 0x2199u); // Arrows
703 for (uint32_t cp : {0x2212u, 0x221Eu, 0x2248u, 0x2260u, 0x2264u, 0x2265u,
704 0x25B2u, 0x25B6u, 0x25BCu, 0x25C0u,
705 0x2605u, 0x2606u,
706 0x2660u, 0x2663u, 0x2665u, 0x2666u,
707 0x2713u, 0x2717u})
708 s.addCodepoint(cp);
709 return s;
710 }
711
712 private:
713 std::vector<int> cps_;
714 };
715
716} // namespace ZenitUI
std::vector< int > build() const
Build a sorted, deduplicated codepoint vector for font loading.
Definition Utf8.hpp:628
CodepointSet & addCodepoint(uint32_t cp)
Add a single valid Unicode scalar value.
Definition Utf8.hpp:571
static CodepointSet ascii()
Printable ASCII (U+0020..U+007E).
Definition Utf8.hpp:639
static CodepointSet symbols()
Common UI, math, arrow, and card/game symbols (←↑→↓ ≤≥≠∞ ▲▼◀▶ ★☆ ♠♥♦♣ ✓✗).
Definition Utf8.hpp:699
CodepointSet & merge(const CodepointSet &other)
Merge all codepoints from other into this set.
Definition Utf8.hpp:615
static CodepointSet typography()
Common European typography (– — ‘ ’ “ ” • … € ™).
Definition Utf8.hpp:663
static CodepointSet greek()
Greek and Coptic (U+0370..U+03FF).
Definition Utf8.hpp:683
void clear()
Remove all codepoints.
Definition Utf8.hpp:622
CodepointSet & addFromUtf8(std::string_view text)
Extract and add every valid printable codepoint from a UTF-8 string.
Definition Utf8.hpp:600
static CodepointSet latinExtendedA()
Latin Extended-A (U+0100..U+017F: Central/Eastern European letters, Œ, œ).
Definition Utf8.hpp:655
static CodepointSet cyrillic()
Cyrillic (U+0400..U+04FF).
Definition Utf8.hpp:691
bool empty() const
true if no codepoints have been added.
Definition Utf8.hpp:625
static CodepointSet defaultLatin()
Default preset: ASCII + Latin-1 + Œ/œ + common European typography.
Definition Utf8.hpp:673
CodepointSet & addRange(uint32_t first, uint32_t last)
Add an inclusive range [first, last], skipping UTF-16 surrogates.
Definition Utf8.hpp:579
static CodepointSet latin1()
Latin-1 Supplement (U+00A0..U+00FF: Western European accents, °, ×, ÷).
Definition Utf8.hpp:647
size_t codepointCount(std::string_view s) noexcept
Count the number of UTF-8 codepoints in s.
Definition Utf8.hpp:225
std::string sanitizeMultiLine(std::string_view src)
Sanitize a pasted string for multi-line text fields.
Definition Utf8.hpp:519
constexpr bool isContinuation(unsigned char b) noexcept
true if b is a UTF-8 continuation byte (10xxxxxx).
Definition Utf8.hpp:27
constexpr bool isValidCodepoint(uint32_t cp) noexcept
true if cp is a valid Unicode scalar value (excludes UTF-16 surrogates).
Definition Utf8.hpp:33
constexpr bool isClusterExtend(uint32_t cp) noexcept
true if cp extends the preceding grapheme cluster.
Definition Utf8.hpp:243
constexpr bool isWordChar(uint32_t cp) noexcept
true if cp belongs to a word (for double-click selection and Ctrl+Arrow).
Definition Utf8.hpp:424
constexpr bool isPrintable(uint32_t cp) noexcept
true if cp is a printable Unicode scalar value accepted by text inputs.
Definition Utf8.hpp:409
size_t nextCodepoint(std::string_view s, size_t pos) noexcept
Advance pos by one UTF-8 codepoint.
Definition Utf8.hpp:203
size_t nextWordBoundary(std::string_view s, size_t pos) noexcept
Move forward past the current/next word (Ctrl+Right / Ctrl+Delete).
Definition Utf8.hpp:469
constexpr bool isRegionalIndicator(uint32_t cp) noexcept
true if cp is a Regional Indicator symbol (U+1F1E6..U+1F1FF).
Definition Utf8.hpp:256
size_t prevCluster(std::string_view s, size_t pos) noexcept
Move pos back by one grapheme cluster.
Definition Utf8.hpp:318
std::string sanitizeSingleLine(std::string_view src)
Sanitize a pasted string for single-line text fields.
Definition Utf8.hpp:497
size_t prevWordBoundary(std::string_view s, size_t pos) noexcept
Move backward to the start of the previous word (Ctrl+Left / Ctrl+Backspace).
Definition Utf8.hpp:444
uint32_t next(std::string_view s, size_t &pos) noexcept
Decode one UTF-8 codepoint at pos and advance pos past it.
Definition Utf8.hpp:175
size_t nextCluster(std::string_view s, size_t pos) noexcept
Advance pos by one grapheme cluster.
Definition Utf8.hpp:268
size_t encode(uint32_t cp, std::string &out)
Append the UTF-8 encoding of cp to out.
Definition Utf8.hpp:60
size_t snapCeil(std::string_view s, size_t pos) noexcept
Clamp pos to s.size() and snap up to the nearest codepoint boundary.
Definition Utf8.hpp:193
size_t decode(std::string_view s, size_t pos, uint32_t &outCp) noexcept
Decode one UTF-8 codepoint starting at byte offset pos.
Definition Utf8.hpp:108
size_t snapFloor(std::string_view s, size_t pos) noexcept
Clamp pos to s.size() and snap down to the nearest codepoint boundary.
Definition Utf8.hpp:183
constexpr size_t seqLenFromLead(unsigned char b) noexcept
Expected UTF-8 byte length from a leading byte (1..4).
Definition Utf8.hpp:43
std::vector< size_t > clusterBoundaries(std::string_view s)
Return all grapheme-cluster byte boundaries in s, starting at 0 and ending at s.size().
Definition Utf8.hpp:389
size_t prevCodepoint(std::string_view s, size_t pos) noexcept
Move pos back by one UTF-8 codepoint.
Definition Utf8.hpp:212