Bounded ZIP archives with Store, Deflate and Zstandard writing and Deflate64 reading, in pure MoonBit.
moon add gaato/zip///|
test "create, read, edit and rewrite a ZIP" {
let archive = @zip.Archive()
archive.add("hello.txt", b"hello", compression=Deflate)
let bytes = @zip.write(archive)
let decoded = @zip.read_all(
bytes,
limits=@zip.ReadLimits(
max_package_bytes=1024 * 1024,
max_entries=100,
max_entry_uncompressed_bytes=1024 * 1024,
max_total_uncompressed_bytes=4 * 1024 * 1024,
),
)
assert_eq(decoded.get("hello.txt"), Some(b"hello"[:]))
assert_true(decoded.replace("hello.txt", b"updated"))
assert_eq(
@zip.read_all(@zip.write(decoded)).get("hello.txt"),
Some(b"updated"[:]),
)
}///|
/// Reads the entry called `name` from a ZIP of `size` bytes, fetching only the
/// ranges the readers ask for.
fn read_entry(
size : UInt64,
fetch : (@zip.ReadRange) -> BytesView,
name : String,
) -> Bytes? raise @zip.ZipError {
let lister = @zip.DirectoryReader(
size,
limits=@zip.DirectoryLimits(max_entries=10000UL),
)
let directory = for input = (b"" : BytesView) {
match lister.advance(input) {
NeedRead(range) => continue fetch(range)
Done(directory) => break directory
}
}
let entries = directory.entries()
let mut index = -1
for i in 0..<entries.length() {
if entries[i].name() == name {
index = i
break
}
}
guard index >= 0 else { return None }
let reader = directory.open_entry(
index,
limits=@zip.EntryReadLimits(max_output_bytes=1UL << 20),
)
let out = FixedArray::make(64 * 1024, b'\x00')
let content = Buffer()
let bytes = for input = (b"" : BytesView) {
let status = reader.step(input, out.mut_view())
// Every step may produce output, `Done` included.
content.write_bytes(Bytes::from_array(out[:reader.last_produced()]))
match status {
NeedRead(range) => continue fetch(range)
NeedMoreOutput => continue b""
Done => break content.to_bytes()
}
}
Some(bytes)
}
///|
test "read one entry through ranges" {
let archive = @zip.Archive()
archive.add("manifest.json", b"{\"version\":1}", compression=Deflate)
archive.add("data.bin", Bytes::make(4096, b'x'), compression=Store)
let zip = @zip.write(archive)
let fetch = fn(range : @zip.ReadRange) -> BytesView {
let offset = range.offset().to_int()
zip[offset:offset + range.length()]
}
assert_eq(
read_entry(zip.length().to_uint64(), fetch, "manifest.json"),
Some(b"{\"version\":1}"),
)
}///|
test "stream an archive to a sink" {
let sink = Buffer()
let writer = @zip.Writer(bytes => sink.write_bytesview(bytes))
writer.add("readme.txt", b"read me", compression=Deflate)
writer.begin_entry("log.txt", compression=Deflate)
for line in [b"one\n", b"two\n"] {
writer.write(line)
}
writer.end_entry()
writer.finish()
let archive = @zip.read_all(sink.to_bytes())
assert_eq(archive.get("log.txt"), Some(b"one\ntwo\n"[:]))
}| compression= | Read by | Notes |
|---|---|---|
| Deflate | Every ZIP tool | The usual choice. |
| Store | Every ZIP tool | No compression. Use it for data that is already compressed (images, video, other archives). |
| Zstandard | Only readers that support method 93 | Often smaller and faster to read, but check that your recipients' tools can open it. |
| Deflate64 | — | Read only. Writing it raises InvalidArgument. |
| Limit | Applies to | Default |
|---|---|---|
| ReadLimits(max_package_bytes~, max_entries~, max_entry_uncompressed_bytes~, max_total_uncompressed_bytes~) | read_all | What an in-memory array holds |
| DirectoryLimits(max_directory_bytes~, max_entries~) | DirectoryReader | None |
| EntryReadLimits(max_output_bytes~) | open_entry | None |
| max_output_bytes | write | Bounds the returned buffer only, not working memory |
type Archivefn Archive::add(self : Archive, name : String, data : BytesView, compression? : Compression) -> Unittype Directoryfn Directory::open_entry(self : Directory, index : Int, limits? : EntryReadLimits) -> EntryReader raise ZipErrortype DirectoryEntrytype DirectoryLimitsfn DirectoryLimits::DirectoryLimits(max_directory_bytes? : UInt64, max_entries? : UInt64) -> DirectoryLimitstype DirectoryReaderfn DirectoryReader::DirectoryReader(archive_size : UInt64, limits? : DirectoryLimits) -> DirectoryReaderfn DirectoryReader::advance(self : DirectoryReader, input : BytesView) -> DirectoryStep raise ZipErrortype Entrytype EntryReadLimitstype EntryReaderfn EntryReader::step(self : EntryReader, input : BytesView, output : MutArrayView[Byte]) -> EntryStep raise ZipErrorpub struct ReadLimits {
max_package_bytes : Int
max_entries : Int
max_entry_uncompressed_bytes : Int
max_total_uncompressed_bytes : Int
}fn ReadLimits::ReadLimits(max_package_bytes? : Int, max_entries? : Int, max_entry_uncompressed_bytes? : Int, max_total_uncompressed_bytes? : Int) -> ReadLimitstype ReadRangetype Writerfn Writer::add(self : Writer, name : String, data : BytesView, compression? : Compression) -> Unit raisefn Writer::begin_entry(self : Writer, name : String, compression? : Compression, size? : UInt64) -> Unit raisepub(all) enum ZipErrorKind {
Truncated
InvalidSignature
MissingEndOfCentral
Corrupt
UnsupportedCompression(Int)
InvalidUtf8
UnsupportedFeature
Codec(ErrorKind)
InvalidRead(expected~ : Int, actual~ : Int)
InvalidEntryIndex(Int)
SizeMismatch
ChecksumMismatch
LimitExceeded(kind~ : LimitKind, limit~ : UInt64, observed~ : UInt64)
Cancelled
InvalidArgument
InvalidState
} derive(Eq, Debug)fn read_all(bytes : BytesView, limits? : ReadLimits, cancelled? : () -> Bool) -> Archive raise ZipErrorInstall
Download zipBounded ZIP archives with Store, Deflate and Zstandard writing and Deflate64 reading, in pure MoonBit.