decodeBase64Bytes function

Uint8List decodeBase64Bytes(
  1. String input,
  2. int start
)

Implementation

Uint8List decodeBase64Bytes(String input, int start) {
  final end = RangeError.checkValidRange(start, null, input.length);
  final length = end - start;
  if (length == 0) {
    return Uint8List(0);
  }
  if ((length & 3) != 0) {
    return base64.decoder.convert(input, start);
  }

  var padding = 0;
  if (input.codeUnitAt(end - 1) == 0x3d) {
    padding++;
    if (input.codeUnitAt(end - 2) == 0x3d) {
      padding++;
    }
  }
  final output = Uint8List((length ~/ 4) * 3 - padding);
  var inputIndex = start;
  var outputIndex = 0;
  final finalQuartet = end - 4;
  while (inputIndex < finalQuartet) {
    final a = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex));
    final b = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex + 1));
    final c = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex + 2));
    final d = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex + 3));
    if ((a | b | c | d) < 0) {
      return base64.decoder.convert(input, start);
    }
    final bits = (a << 18) | (b << 12) | (c << 6) | d;
    output[outputIndex] = bits >> 16;
    output[outputIndex + 1] = bits >> 8;
    output[outputIndex + 2] = bits;
    inputIndex += 4;
    outputIndex += 3;
  }

  final a = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex));
  final b = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex + 1));
  if ((a | b) < 0) {
    return base64.decoder.convert(input, start);
  }
  if (padding == 2) {
    if (input.codeUnitAt(inputIndex + 2) != 0x3d ||
        input.codeUnitAt(inputIndex + 3) != 0x3d ||
        (b & 0x0f) != 0) {
      return base64.decoder.convert(input, start);
    }
    output[outputIndex] = (a << 2) | (b >> 4);
    return output;
  }

  final c = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex + 2));
  if (c < 0) {
    return base64.decoder.convert(input, start);
  }
  output[outputIndex] = (a << 2) | (b >> 4);
  output[outputIndex + 1] = (b << 4) | (c >> 2);
  if (padding == 1) {
    if (input.codeUnitAt(inputIndex + 3) != 0x3d || (c & 0x03) != 0) {
      return base64.decoder.convert(input, start);
    }
    return output;
  }

  final d = _decodeBase64CodeUnit(input.codeUnitAt(inputIndex + 3));
  if (d < 0) {
    return base64.decoder.convert(input, start);
  }
  output[outputIndex + 2] = (c << 6) | d;
  return output;
}