radlang — Compression (compress)

The compress namespace provides gzip and zlib(deflate) stream compression, plus ZIP archive create/extract. It is a compiler-intrinsic namespace — available everywhere with no import — backed by a vendored, statically-linked miniz (no external zlib dependency).

For language fundamentals see the Overview. The HTTP server uses this same codec to gzip responses automatically; see HTTP.


Overview

Method Returns Description
compress.gzip(string|byte[] input [, map meta]) byte[] Compress to a gzip stream (RFC 1952)
compress.gunzip(byte[] data) string | byte[] Decompress a gzip stream
compress.deflate(string|byte[] input) byte[] Compress to a zlib stream (RFC 1950)
compress.inflate(byte[] data) string | byte[] Decompress a zlib stream
compress.gzipInfo(byte[] data) string Read a gzip stream’s metadata as JSON
compress.unzip(string|byte[] src, string destDir) int Extract a ZIP archive to a directory; returns file count
compress.zip(string destPath, string[] files) int Create a ZIP archive from files; returns count added
compress.zipEntries(string|byte[] src) string[] List an archive’s entry names, in archive order
compress.zipRead(string|byte[] src, string name [, long maxBytes]) byte[] Read one entry into memory
compress.zipBytes(string[] names, byte[][] contents) byte[] Build a ZIP archive in memory from named entries

gzip/gunzip produce and consume the gzip container (magic header + CRC-32 + size trailer) that HTTP labels Content-Encoding: gzip. deflate/inflate use the zlib container HTTP labels Content-Encoding: deflate.


Text and binary (input + output)

Compression accepts either a string or a byte[] — the same method handles both:

byte[] a = compress.gzip("some text")        // from a string
byte[] b = compress.gzip(fs.readBytesSync("photo.raw"))   // from bytes

Decompression’s output type is chosen by the declaration target — declare the result string for text, or byte[] for binary-safe bytes:

string text = compress.gunzip(a)   // text (NUL-terminated)
byte[] raw  = compress.gunzip(b)   // raw bytes, safe for binary payloads

Prefer the byte[] form for any payload that may contain NUL bytes (images, audio, serialized binary) — the string form is meant for text and stops at the first NUL.

Round-trip a string:

fn main() {
    string original = "the quick brown fox jumps over the lazy dog"
    byte[] packed = compress.gzip(original)
    string restored = compress.gunzip(packed)
    sys.output(restored)   // the quick brown fox jumps over the lazy dog
}

Persist a compressed payload with the fs byte APIs:

fn main() {
    string report = '{"ok":true}'
    byte[] packed = compress.gzip(report)
    fs.writeBytesSync("report.json.gz", packed)

    byte[] onDisk = fs.readBytesSync("report.json.gz")
    string restored = compress.gunzip(onDisk)
}

deflate / inflate behave the same over the zlib container.


gzip metadata

By default gzip writes a minimal, deterministic header (no timestamp, no filename) so the same input always yields the same bytes — useful for caching and ETags. Pass an optional metadata map to embed a filename, modification time, or comment in the gzip header:

byte[] gz = compress.gzip(body, {
    "name": "report.json",
    "mtime": "1730400000",
    "comment": "nightly export"
})

name and comment are text and mtime is unix seconds, written as a string (map values are strings). A comment cannot sit inside a multi-line literal, so describe the keys outside it.

Read a gzip stream’s metadata back as a JSON object with gzipInfo (missing fields come back as "" / 0):

string info = compress.gzipInfo(gz)
// {"name":"report.json","mtime":1730400000,"comment":"nightly export"}

// Parse it into a struct you define, or navigate it dynamically with json.*
type GzipMeta { string name, long mtime, string comment }
GzipMeta m = json.parse<GzipMeta>(info)
sys.output(m.name)   // report.json

deflate (zlib) has no metadata slot, so there’s nothing to set there.


ZIP archives

Create a ZIP from a list of file paths (each stored under its basename), and extract an archive to a directory. Both zip and unzip return the number of files processed.

fn main() {
    int added = compress.zip("bundle.zip", ["a.txt", "assets/logo.png"])
    // bundle.zip now contains "a.txt" and "logo.png"

    int files = compress.unzip("bundle.zip", "out/")
    sys.output(files)   // 2
}

zip skips a path that cannot be read and counts only the files it added (0 when none could be). unzip returns -1 when the source is not a ZIP archive.

unzip accepts the archive as a path or as byte[], so you can extract one you already hold in memory (e.g. a download):

byte[] archive = fs.readBytesSync("downloads/pkg.zip")   // or bytes from any source
int files = compress.unzip(archive, "pkg/")

Extraction is hardened against zip-slip: entries with absolute paths or .. components are skipped rather than written outside destDir. Parent directories are created as needed.

Strict bounded extraction

fs.mkdir("staging")
int files = compress.unzip(archive, "staging", 5000, Long(1073741824))
if (files < 0) {
    // Remove the entire staging tree. Do not publish it or mark it complete.
}

The additive four-argument overload accepts a path or byte[], a destination, maxEntries, and maxExpandedBytes (limits are int or long). It returns the regular-file count on complete success, or -1 on any failure. Negative limits fail; exact limits are allowed. Directories count toward the entry budget; empty regular files count as files but consume no expanded bytes. The two-argument API retains its existing best-effort behavior.

Strict mode preflights entry count, aggregate declared sizes and local headers, then checks the aggregate actual output budget before each write. CRC errors, truncation, unsupported/encrypted entries, symlink/special-file metadata and unsafe paths fail the operation. Directory entries must be empty stored entries. Repeated separators and . components normalize; absolute paths, .., backslashes, drive/colon paths and embedded NULs are rejected.

Use an existing, trusted destination directory, preferably a fresh staging folder per extraction. Strict mode refuses a symlink as that directory or any descendant, walks descendants through directory file descriptors, and creates files exclusively: existing files (including hardlinks), duplicate normalized file names and symlink destinations fail rather than being overwritten. The caller controls the trusted ancestors of the destination path.

Failure is not a transaction: the failed file is removed but earlier files and created directories can remain. Always discard failed staging output; only publish a successful staging tree after checking required application files. Neither an upload-size limit nor a later disk scan replaces these expanded-output limits.

In-memory, per-entry access

zipEntries, zipRead and zipBytes work on archives in memory (or one opened by path) without extracting anything to disk:

byte[] raw = [0, 1, 2, 255]
byte[][] contents = ["hello".toBytes(), raw]   // a literal [0, 1, 2, 255] inline would be int[]
byte[] archive = compress.zipBytes(["notes/a.txt", "data.bin"], contents)

string[] names = compress.zipEntries(archive)        // ["notes/a.txt", "data.bin"]
byte[] bin = compress.zipRead(archive, "data.bin")   // [0, 1, 2, 255]
  • zipEntries(src) returns every entry name exactly as stored, directories included (they end in /). Names come from the archive and may be hostile (../x, absolute paths): treat them as labels, never join them onto a path without validating. src is a path or a byte[].
  • zipRead(src, name, maxBytes?) returns one entry’s bytes. The name must match exactly; a directory or empty entry reads as an empty list. The entry’s declared size is checked against maxBytes (default 256 MiB) before any memory is allocated, and the data is checked against its CRC-32, so a lying header or corrupt data cannot produce a huge allocation or silently wrong bytes.
  • zipBytes(names, contents) builds a standard ZIP (deflate, level 6). names[i] pairs with contents[i]; a name ending in / creates a directory entry and must have empty contents. Output is deterministic: entries carry a fixed modification time, so identical input gives identical bytes (cacheable, usable in ETags). Limits: 65,000 entries, 2 GiB of content.

All three throw a catchable Error instead of returning a sentinel: not a ZIP archive or unreadable path, no such entry, entry larger than maxBytes, encrypted or unsupported entry, corrupt data, and (for zipBytes) the cases below.

Names zipBytes refuses (so an archive it makes can never zip-slip a later unzip, by this runtime or any other tool): empty names, names over 1024 bytes, absolute paths, empty (a//b), . or .. components, backslashes, :, control characters, and duplicate names. Dots inside a component (a..b, .hidden) are fine.

Extraction safety

Both extraction modes keep every write inside the destination:

  • unzip(src, dest) skips entries with absolute paths or a .. in the name, and (new) entries whose target path passes through a symbolic link that already exists under dest, so a link planted in the destination cannot redirect a write. dest itself may be a link; you own the trusted ancestors of the destination.
  • unzip(src, dest, maxEntries, maxExpandedBytes) is stricter: it fails the whole extraction (returns -1) on any unsafe name, symlink, special file, existing file or overflow, as described above.

Notes

  • Compression level is the balanced default (zlib level 6); it is not currently configurable.
  • Decompression is size-safe: a malformed stream yields an empty byte[], or "" when the result is a string (before 1.40.28 the string form crashed on malformed input), rather than crashing.
  • HTTP is automatic. You rarely need compress for web responses — the server gzips eligible bodies and the client transparently inflates them. Reach for this namespace to compress files, cache entries, message payloads, or to pack/unpack archives outside the HTTP path.
  • ZIP scope. Extract-all, create-from-paths, and in-memory listing, per-entry reads and creation. ZIP64, encryption and appending to an existing archive are not supported.