convert method

  1. @override
List<int> convert(
  1. covariant List<int> encoded
)
override

Converts encoded array of numbers with bit-length of source to an array of numbers with bit-length of target. The encoded array will be treated as a sequence of bits to convert.

If the encoded array contains negative numbers or numbers having more than the source bits, it will be treated as the end of the input sequence.

After consuming all of input sequence, if there are some non-zero partial word remains, it will throw FormatException.

Implementation

@override
List<int> convert(List<int> encoded) {
  var bytes = encoded is Uint8List ? encoded : Uint8List.fromList(encoded);
  int len = bytes.length;
  var out = Uint32List(len);

  int x, n = 0, p = 0;
  while (p < len) {
    x = bytes[p];
    // Case: 1-byte ASCII run
    if (x <= 0x7F) {
      out[n++] = x;
      p++;
    }
    // Case: 2-bytes
    else if ((x & 0xE0) == 0xC0) {
      out[n++] = _decode2(bytes, len, p, x);
      p += 2;
    }
    // Case: 3-bytes UTF-16
    else if ((x & 0xF0) == 0xE0) {
      out[n++] = _decode3(bytes, len, p, x);
      p += 3;
    }
    // Case: 4-byte UTF-16 surrogate pair
    else if ((x & 0xF8) == 0xF0) {
      out[n++] = _decode4(bytes, len, p, x);
      p += 4;
    }
    // Case: 5 or more bytes
    else {
      throw FormatException('Invalid code $x at $p');
    }
  }
  if (n == len) {
    return out;
  }
  return out.sublist(0, n);
}