decodeUtf8Strict function
- Uint8List bytes
Strictly decodes UTF-8 bytes to a Dart String, returning null if they
are not well-formed UTF-8 per RFC 3629 โ the decode-side twin of
encodeUtf8Strict, and never lossy: no U+FFFD substitution, no dropped
byte (CORELIB_PLAN ยง6.4).
It validates once and builds the string in the same pass โ rather than a
separate utf8Valid scan of the whole payload followed by an independent
transcode of it from byte zero. (A string the decoder writes into an
InlineString is already validated there; this is for bytes of the
caller's own.)
The ASCII fast path is why: a byte below 0x80 is a complete, trivially
valid UTF-8 sequence, so one scan settles validity and the transcode for
an all-ASCII payload โ String.fromCharCodes builds the one-byte string
directly, touching neither the general validator nor the UTF-8 decoder.
Field names, ids, tags and most identifiers are exactly that. A payload that
does turn multi-byte is validated only from its first non-ASCII byte,
which is a legal resync point precisely because every byte before it stands
alone.
Implementation
String? decodeUtf8Strict(Uint8List bytes) {
final n = bytes.length;
var i = 0;
while (i < n && bytes[i] < 0x80) {
i++;
}
if (i == n) return String.fromCharCodes(bytes);
if (!utf8Valid(bytes, i)) return null;
return utf8.decode(bytes);
}