encode static method

String encode(
  1. List<int> data, {
  2. bool noPadding = false,
  3. bool urlSafe = false,
})

Encodes data to a Base64 string.

noPadding: if true, omits the trailing = padding. urlSafe: if true, uses -/_ in place of +//.

Implementation

static String encode(
  List<int> data, {
  bool noPadding = false,
  bool urlSafe = false,
}) {
  if (data.isEmpty) return '';

  final table = urlSafe ? urlSafeCodes : standardCodes;
  final fullGroups = data.length ~/ 3;
  final remainder = data.length % 3; // 0, 1, or 2 leftover bytes

  final outLen =
      noPadding
          ? fullGroups * 4 + (remainder == 0 ? 0 : remainder + 1)
          : (fullGroups + (remainder == 0 ? 0 : 1)) * 4;

  final out = List<int>.filled(outLen, 0);
  var o = 0;
  var i = 0;
  final fullEnd = fullGroups * 3;

  while (i < fullEnd) {
    final chunk =
        ((data[i] & 0xFF) << 16) |
        ((data[i + 1] & 0xFF) << 8) |
        (data[i + 2] & 0xFF);
    out[o++] = table[(chunk >> 18) & 0x3F];
    out[o++] = table[(chunk >> 12) & 0x3F];
    out[o++] = table[(chunk >> 6) & 0x3F];
    out[o++] = table[chunk & 0x3F];
    i += 3;
  }

  if (remainder == 1) {
    final chunk = (data[i] & 0xFF) << 16;
    out[o++] = table[(chunk >> 18) & 0x3F];
    out[o++] = table[(chunk >> 12) & 0x3F];
    if (!noPadding) {
      out[o++] = _equalsCode;
      out[o++] = _equalsCode;
    }
  } else if (remainder == 2) {
    final chunk = ((data[i] & 0xFF) << 16) | ((data[i + 1] & 0xFF) << 8);
    out[o++] = table[(chunk >> 18) & 0x3F];
    out[o++] = table[(chunk >> 12) & 0x3F];
    out[o++] = table[(chunk >> 6) & 0x3F];
    if (!noPadding) {
      out[o++] = _equalsCode;
    }
  }

  return String.fromCharCodes(out);
}