buildPack function
Builds a pack. files maps logical path -> original bytes.
compress is zlib deflate (dart:io's zlib in the packer).
randomBytes supplies nonces (Random.secure in the packer).
Implementation
Uint8List buildPack(
Map<String, Uint8List> files,
PackKeys keys, {
required List<int> Function(List<int>) compress,
required Uint8List Function(int) randomBytes,
}) {
final entries = <PackEntry>[];
final data = BytesBuilder(copy: false);
var offset = 0;
final paths = files.keys.toList()..sort();
for (final path in paths) {
final original = files[path]!;
var stored = original;
var compressed = false;
final z = compress(original);
// Only keep compression when it saves at least 5% (JPGs/PNGs won't).
if (z.length < original.length * 0.95) {
stored = Uint8List.fromList(z);
compressed = true;
}
final nonce = randomBytes(12);
final cipher = chacha20(keys.encKey, nonce, stored);
entries.add(PackEntry(
path: path,
offset: offset,
storedLength: cipher.length,
originalLength: original.length,
compressed: compressed,
nonce: nonce,
mac: entryMac(keys.macKey, path, nonce, cipher),
));
data.add(cipher);
offset += cipher.length;
}
final indexNonce = randomBytes(12);
final indexPlain = utf8.encode(jsonEncode([for (final e in entries) e.toJson()]));
final indexCipher = chacha20(keys.encKey, indexNonce, indexPlain);
final out = BytesBuilder(copy: false)
..add(owpMagic)
..add(indexNonce)
..add(_u32le(indexCipher.length))
..add(indexMac(keys.macKey, indexNonce, indexCipher.length, indexCipher))
..add(indexCipher)
..add(data.takeBytes());
return out.takeBytes();
}