decodeData method

  1. @override
Uint8List decodeData(
  1. String part
)
override

Decodes base64 part data leniently.

RFC 2045 section 6.8 requires decoders to ignore any character outside of the base64 alphabet, e.g. line breaks or white space, and a missing padding is added, so that broken input does not throw.

Implementation

@override
Uint8List decodeData(final String part) {
  final buffer = StringBuffer();
  for (final code in part.codeUnits) {
    if (_isBase64Char(code)) {
      buffer.writeCharCode(code);
    } else if (code == AsciiRunes.runeEquals) {
      // the padding ends the data
      break;
    }
  }
  var cleaned = buffer.toString();
  final remainder = cleaned.length % 4;
  if (remainder == 1) {
    // a single trailing character cannot encode anything
    cleaned = cleaned.substring(0, cleaned.length - 1);
  } else if (remainder > 1) {
    cleaned = cleaned.padRight(cleaned.length + 4 - remainder, '=');
  }
  try {
    return base64.decode(cleaned);
  } on FormatException catch (e) {
    print('unable to decode base64 data: ${e.message}');

    return Uint8List(0);
  }
}