restoreBytes function

Uint8List restoreBytes(
  1. Uint8List bytes
)

Decompresses a Uint8List that was compressed by shrinkBytes.

Reads the compression method from the first byte and applies the appropriate decompression algorithm. Supports legacy compression methods from versions prior to 1.5.6.

Returns the original uncompressed data. Throws ArgumentError if input is empty, UnsupportedError for unknown compression methods, or FormatException if data is corrupted.

Implementation

Uint8List restoreBytes(Uint8List bytes) {
  if (bytes.isEmpty) {
    throw ArgumentError('Input is empty');
  }

  final method = bytes[0];
  final data = bytes.sublist(1);

  if (method == _CompressionMethod.identity) {
    return data; // No compression
  }

  final zLibDecoder = ZLibDecoder();

  if (method == _CompressionMethod.zlib) {
    return Uint8List.fromList(zLibDecoder.decodeBytes(data));
  } else if (_CompressionMethod.isLegacy(method)) {
    // Legacy 1..9 could be zlib or gzip, try zlib first, then gzip.
    try {
      return Uint8List.fromList(zLibDecoder.decodeBytes(data));
    } catch (_) {
      final gZipDecoder = GZipDecoder();
      try {
        return Uint8List.fromList(gZipDecoder.decodeBytes(data));
      } catch (e) {
        throw FormatException('Failed to decode LEGACY method=$method: $e');
      }
    }
  } else {
    throw UnsupportedError('Unknown compression method byte: $method');
  }
}