decodeBase64URL function

String decodeBase64URL(
  1. String s,
  2. int i
)

Implementation

String decodeBase64URL(String s, int i) {
  if (s.length < 2) {
    throw ArgumentError(
        "Input (s = ${s}) is not tightly packed because s.length < 2");
  }
  List<int> bits = base64UrlStringToBitVector(s);

  final firstCharOffset = i % 4;
  if (firstCharOffset == 0) {
    // skip
  } else if (firstCharOffset == 1) {
    bits = bits.sublist(2);
  } else if (firstCharOffset == 2) {
    bits = bits.sublist(4);
  } else {
    // (offset == 3)
    throw ArgumentError(
        "Input (s = ${s}) is not tightly packed because i%4 = 3 (i = ${i}))");
  }

  final lastCharOffset = (i + s.length - 1) % 4;
  if (lastCharOffset == 3) {
    // skip
  } else if (lastCharOffset == 2) {
    bits = bits.sublist(0, bits.length - 2);
  } else if (lastCharOffset == 1) {
    bits = bits.sublist(0, bits.length - 4);
  } else {
    // (offset == 0)
    throw ArgumentError(
      "Input (s = ${s}) is not tightly packed because (i + s.length - 1)%4 = 0 (i = ${i}))",
    );
  }

  if (bits.length % 8 != 0) {
    throw ArgumentError("We should never reach here...");
  }

  final bytes = <int>[];
  for (int i = 0; i < bits.length; i += 8) {
    final bitChunk = bits.sublist(i, i + 8);

    // Convert the 8-bit chunk to a byte and add it to the bytes array
    final byte = int.parse(bitChunk.join(''), radix: 2);
    bytes.add(byte);
  }
  return utf8.decode(bytes);
}