decode static method
Decodes bytes as ASCII.
allowMalformed: if true, any byte outside the ASCII range is
replaced with U+FFFD (the standard replacement character) instead of
throwing.
Throws Utf8Exception if bytes contains a byte outside the ASCII
range (0x00..0x7F) and allowMalformed is false (the default).
Implementation
static String decode(List<int> bytes, {bool allowMalformed = false}) {
// Output is always exactly one char per input byte - no need for a
// separate first pass to count length before allocating (that count
// is always just bytes.length; the original computed it anyway).
final chars = List<int>.filled(bytes.length, 0);
for (var i = 0; i < bytes.length; i++) {
final b = bytes[i];
if (b <= 0x7F) {
chars[i] = b;
} else if (allowMalformed) {
chars[i] = 0xFFFD;
} else {
throw BuError(
DefaultErrorType.badUtf8,
'Invalid ASCII string.',
details: {
'reason':
'byte 0x${b.toRadixString(16)} at index $i is outside the ASCII range',
},
);
}
}
return String.fromCharCodes(chars);
}