encode static method
Encodes str to ASCII bytes.
Throws Utf8Exception if str contains any character outside the
ASCII range (0x00..0x7F).
Implementation
static BuBytes encode(String str) {
// Output is always exactly one byte per input character - no
// variable-length expansion like UTF-8 has - so the buffer can be
// sized exactly up front instead of grown incrementally.
final bytes = BuBytes.fill(str.length, 0);
for (var i = 0; i < str.length; i++) {
final codeUnit = str.codeUnitAt(i);
if (codeUnit > 0x7F) {
throw BuError(
DefaultErrorType.badUtf8,
'Invalid ASCII string.',
details: {
'reason':
'character "${str[i]}" at index $i is outside the ASCII range',
},
);
}
bytes[i] = codeUnit;
}
return bytes;
}