convert method
Converts input array of numbers with bit-length of source to an array
of numbers with bit-length of target. The input array will be treated
as a sequence of bits to convert.
After consuming all of input sequence, if there are some non-zero partial word remains, 0 will be padded on the right to make the final word.
Implementation
@override
Uint8List convert(List<int> input) {
int len = input.length;
int l = 0, p = 0, x, y;
var out = Uint8List(len << 2);
while (p < len) {
x = input[p];
// Case: negative code
if (x < 0) {
throw FormatException('Negative code $x at $p');
}
// Case: Exceeds range
else if (x > 0x0010FFFF) {
throw FormatException('Invalid code $x at $p');
}
// Case: 1-byte ASCII run
else if (x <= 0x7F) {
out[l++] = x;
p++;
}
// Case: 2-byte
else if (x <= 0x7FF) {
out[l++] = 0xC0 | (x >>> 6);
out[l++] = 0x80 | (x & 0x3F);
p++;
}
// Case: 3-byte (rest of the Basic Multilingual Plane, sans surrogates)
else if (x <= 0xFFFF && (x < 0xD800 || x > 0xDFFF)) {
out[l++] = 0xE0 | (x >>> 12);
out[l++] = 0x80 | ((x >>> 6) & 0x3F);
out[l++] = 0x80 | (x & 0x3F);
p++;
}
// Case: 4-byte, either a scalar in U+10000..U+10FFFF or a UTF-16
// high surrogate combined with the following low surrogate into one.
else {
if (x <= 0xDBFF) {
p++;
if (p >= len) {
throw FormatException('Unpaired high surrogate $x at ${p - 1}');
}
y = input[p];
if (y < 0xDC00 || y > 0xDFFF) {
throw FormatException('Invalid surrogate pair ($x, $y) at $p');
}
x = 0x10000 + (((x - 0xD800) << 10) | (y - 0xDC00));
} else if (x <= 0xDFFF) {
throw FormatException('Unpaired low surrogate $x at $p');
}
out[l++] = 0xF0 | (x >>> 18);
out[l++] = 0x80 | ((x >>> 12) & 0x3F);
out[l++] = 0x80 | ((x >>> 6) & 0x3F);
out[l++] = 0x80 | (x & 0x3F);
p++;
}
}
if (l == out.length) {
return out;
}
return out.sublist(0, l);
}