int writeCharCode(final Uint8List buffer, int index, final int code) {
if (code < 0) {
throw new ArgumentError('Invalid character code: $code');
} else if (code <= _UTF8_ONE_BYTE_LIMIT) {
buffer[index++] = code;
} else if (_isLeadSurrogate(code)) {
throw new UnimplementedError('Surrogates are not supported: $code');
} else if (code <= _UTF8_TWO_BYTE_LIMIT) {
buffer[index++] = 0xC0 | (code >> 6);
buffer[index++] = 0x80 | (code & 0x3f);
} else if (code <= _UTF8_THREE_BYTE_LIMIT) {
buffer[index++] = 0xE0 | (code >> 12);
buffer[index++] = 0x80 | ((code >> 6) & 0x3f);
buffer[index++] = 0x80 | (code & 0x3f);
} else {
throw new ArgumentError('Invalid character code: $code');
}
return index;
}
// UTF-8 constants.
const int _UTF8_ONE_BYTE_LIMIT = 0x7f; // 7 bits
const int _UTF8_TWO_BYTE_LIMIT = 0x7ff; // 11 bits
const int _UTF8_THREE_BYTE_LIMIT = 0xffff; // 16 bits
const int _UTF8_FOUR_BYTE_LIMIT = 0x10ffff; // 21 bits, truncated to Unicode max.
// UTF-16 constants.
const int _UTF8_SURROGATE_TAG_MASK = 0xFC00;
const int _UTF8_SURROGATE_VALUE_MASK = 0x3FF;
const int _UTF8_LEAD_SURROGATE_MIN = 0xD800;
bool _isLeadSurrogate(int codeUnit) =>
(codeUnit & _UTF8_SURROGATE_TAG_MASK) == _UTF8_LEAD_SURROGATE_MIN;
int writeString(final Uint8List buffer, int index, final String value) {
final length = value.length;
for (var index = 0; index < length; index++)
index = writeCharCode(buffer, index, value.codeUnitAt(index));
return index;
}