decode method
Decodes a valid UTF-8 octet sequence in input directly to a String.
This is a faster equivalent of String.fromCharCodes(convert(...))
that emits UTF-16 code units in a single pass. Throws a FormatException
if input is not a valid UTF-8 octet sequence.
Implementation
String decode(Uint8List input) {
int len = input.length;
if (len == 0) return '';
int x, y, n = 0, p = 0;
var units = Uint16List(len);
while (p < len) {
x = input[p];
// Case: 1-byte ASCII run
if (x <= 0x7F) {
units[n++] = x;
p++;
}
// Case: 2-bytes
else if ((x & 0xE0) == 0xC0) {
units[n++] = _decode2(input, len, p, x);
p += 2;
}
// Case: 3-bytes
else if ((x & 0xF0) == 0xE0) {
units[n++] = _decode3(input, len, p, x);
p += 3;
}
// Case: 4-bytes UTF-16 surrogate pair
else if ((x & 0xF8) == 0xF0) {
y = _decode4(input, len, p, x) - 0x10000;
units[n++] = 0xD800 | (y >> 10);
units[n++] = 0xDC00 | (y & 0x3FF);
p += 4;
}
// Case: 5 or more bytes
else {
throw FormatException('Invalid code $x at $p');
}
}
return String.fromCharCodes(units, 0, n);
}