encode static method
Encodes s to UTF-8 bytes. Single pass: each code point is resolved
once and its 1-4 UTF-8 bytes written immediately - no separate
length-counting pass first.
Implementation
static BuBytes encode(String s) {
final out = BuBytes.empty();
var i = 0;
while (i < s.length) {
final (codePoint, next) = _nextCodePoint(s, i);
i = next;
if (codePoint <= 0x7F) {
out.add(codePoint);
} else if (codePoint <= 0x7FF) {
out.add(0xC0 | (codePoint >> 6));
out.add(0x80 | (codePoint & 0x3F));
} else if (codePoint <= 0xFFFF) {
out.add(0xE0 | (codePoint >> 12));
out.add(0x80 | ((codePoint >> 6) & 0x3F));
out.add(0x80 | (codePoint & 0x3F));
} else {
out.add(0xF0 | (codePoint >> 18));
out.add(0x80 | ((codePoint >> 12) & 0x3F));
out.add(0x80 | ((codePoint >> 6) & 0x3F));
out.add(0x80 | (codePoint & 0x3F));
}
}
return out;
}