encodeUtf8Strict function
- String s
Strictly encodes a Dart String to UTF-8 bytes, returning null if the
string contains an unpaired surrogate (the only way a Dart String can
fail to be valid Unicode). Never emits U+FFFD — a strict/fatal encoder as
CORELIB_PLAN §6.4 requires (Dart's utf8.encode/TextEncoder are lossy on
unpaired surrogates and must not be used here).
Implementation
Uint8List? encodeUtf8Strict(String s) {
final units = s.codeUnits;
final n = units.length;
// Worst case 3 bytes per BMP code unit; surrogate pairs collapse 2 units → 4
// bytes, so 3*n is always sufficient.
final out = Uint8List(n * 3);
var o = 0;
var i = 0;
while (i < n) {
final c = units[i++];
if (c < 0x80) {
out[o++] = c;
} else if (c < 0x800) {
out[o++] = 0xC0 | (c >> 6);
out[o++] = 0x80 | (c & 0x3F);
} else if (c >= 0xD800 && c <= 0xDBFF) {
// High surrogate: must be followed by a low surrogate.
if (i >= n) return null;
final c2 = units[i];
if (c2 < 0xDC00 || c2 > 0xDFFF) return null;
i++;
final cp = 0x10000 + (((c - 0xD800) << 10) | (c2 - 0xDC00));
out[o++] = 0xF0 | (cp >> 18);
out[o++] = 0x80 | ((cp >> 12) & 0x3F);
out[o++] = 0x80 | ((cp >> 6) & 0x3F);
out[o++] = 0x80 | (cp & 0x3F);
} else if (c >= 0xDC00 && c <= 0xDFFF) {
return null; // lone low surrogate
} else {
out[o++] = 0xE0 | (c >> 12);
out[o++] = 0x80 | ((c >> 6) & 0x3F);
out[o++] = 0x80 | (c & 0x3F);
}
}
return Uint8List.sublistView(out, 0, o);
}