base64StringToBytes method

List<int> base64StringToBytes (String input, [ bool ignoreInvalidCharacters = true ])

Implementation

static List<int> base64StringToBytes(String input,
    [bool ignoreInvalidCharacters = true]) {
  int len = input.length;
  if (len == 0) {
    return new List<int>(0);
  }

  // Count '\r', '\n' and illegal characters, For illegal characters,
  // if [ignoreInvalidCharacters] is false, 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 && !ignoreInvalidCharacters) {
        throw new FormatException('Invalid character: ${input[i]}');
      }
    }
  }

  if ((len - extrasLen) % 4 != 0) {
    throw new FormatException('''Size of Base 64 characters in Input
        must be a multiple of 4. Input: $input''');
  }

  // Count pad characters, ignore illegal characters at the end.
  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;
  List<int> out = new List<int>(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;
}