Uint8List decode(String input)

Source

static Uint8List decode(String input) {
  if (input == null) {
    return null;
  }
  int len = input.length;
  if (len == 0) {
    return new Uint8List(0);
  }

  // Count '\r', '\n' and illegal characters, For illegal characters,
  // throw an exception.
  int extrasLen = 0;
  for (int i = 0; i < len; i++) {
    int c = _decodeTable[input.codeUnitAt(i)];
    if (c < 0) {
      extrasLen++;
      if (c == -2) {
        return null;
      }
    }
  }

  int lenmis = (len - extrasLen) % 4;
  if (lenmis == 2) {
    input = '$input==';
    len += 2;
  } else if (lenmis == 3) {
    input = '$input=';
    len += 1;
  } else if (lenmis == 1) {
    return null;
  }

  // Count pad characters.
  int padLength = 0;
  for (int i = len - 1; i >= 0; i--) {
    int currentCodeUnit = input.codeUnitAt(i);
    if (_decodeTable[currentCodeUnit] > 0) break;
    if (currentCodeUnit == PAD) padLength++;
  }
  int outputLen = (((len - extrasLen) * 6) >> 3) - padLength;
  Uint8List out = new Uint8List(outputLen);

  for (int i = 0, o = 0; o < outputLen;) {
    // Accumulate 4 valid 6 bit Base 64 characters into an int.
    int x = 0;
    for (int j = 4; j > 0;) {
      int c = _decodeTable[input.codeUnitAt(i++)];
      if (c >= 0) {
        x = ((x << 6) & 0xFFFFFF) | c;
        j--;
      }
    }
    out[o++] = x >> 16;
    if (o < outputLen) {
      out[o++] = (x >> 8) & 0xFF;
      if (o < outputLen) out[o++] = x & 0xFF;
    }
  }
  return out;
}