Compress
import "std/data" (included in import "std") · namespace std.data
gzip, zlib and raw deflate compression, using the system's zlib (loaded the first time it is needed). The formats are the ones .gz files, HTTP Content-Encoding and zip archives use, so the results interoperate with gzip, browsers and other languages.
import "std"
fn main() {
let text = Str.repeat("the same words again and again ", 300)
let packed = Compress.gzipText(text)
print("${text.length} bytes -> under 1%: ${packed.size() * 100 < text.length}, gzip: ${Compress.isGzip(packed)}")
print(Compress.gunzipText(packed) == text)
let z = Compress.deflate(Bytes.fromString(text), 9)
print(Compress.inflate(z).size())
try {
Compress.decompress(Compress.gzipText(Str.repeat("a", 100000)), 1000)
} catch (e: ValueError) {
print(e.message())
}
}9300 bytes -> under 1%: true, gzip: true
true
9300
the data decompresses to more than the limit- gzip:
gzip(data[, level]),gunzip(data),gzipText,gunzipText. Levels go from 1 (fastest) to 9 (smallest), 0 stores without compressing; the default is 6. - zlib (HTTP's
deflate):deflate(data[, level])andinflate(data). Raw deflate (no header, as in zip files):deflateRawandinflateRaw. - Any of them:
decompress(data, maxBytes)detects the format and stops withValueErrorpastmaxBytes, so a small hostile input cannot expand into gigabytes (gunzipandinflateallow up to 1 GiB). isGzip(data)andisZlib(data)look at the first bytes.- Corrupt or truncated input throws
ValueErrorsaying which. Without zlib,Compress.available()is false and the calls throwStateError. HttpServer.compress(true)andHttpClientuse this for HTTP compression.
Streams
GzipWriter and GzipReader compress and decompress a piece at a time, so a file of any size passes through in a little memory: 200 MB compressed in pieces peaks at about 2 MB, against 210 MB for Compress.gzip on the whole, at the same speed.
import "std"
fn main() {
let path = Dir.temp() + "/notes.gz"
let gz = GzipWriter.toFile(path) // or new GzipWriter(fn(b: Bytes) { ... })
for (i in 0..3) { gz.writeString("line ${i}\n") }
gz.finish() // writes the end; closes the file
print("${gz.bytesIn} bytes in")
let r = GzipReader.fromFile(path) // or new GzipReader(fn(n: int) -> Bytes { ... })
while (true) {
let part = r.read(4) // up to 4 bytes at a time
if (part.isEmpty()) { break }
print(Str.replace(part.toString(), "\n", "|"))
}
new File(path).delete()
}21 bytes in
line
0|l
ine
1|li
ne 2
|- Sinks and sources are functions, so streams chain: a TarWriter writing into a
GzipWritermakes a.tar.gz.GzipReader's source is asked for up to n bytes and returns an emptyBytesat the end. - Members written one after another (as
cat a.gz b.gzmakes) read as one stream. Data that ends too soon, or is not gzip, is aValueError.
API
class Compress
gzip, zlib and raw deflate compression.
Static members
static fn available() -> bool— Whether zlib could be loaded (compression works).static fn libraryVersion() -> string— The zlib version in use ("1.3.1"), "" without zlib.static fn gzip(data: Bytes) -> Bytes— gzip-compressed (the .gz and HTTP "gzip" format) at the default level 6.static fn gzip(data: Bytes, level: int) -> Bytes— gzip at a level from 1 (fastest) to 9 (smallest); 0 stores without compressing.static fn gunzip(data: Bytes) -> Bytes— The bytes of gzip (or zlib) data, at most 1 GiB; ValueError when corrupt.static fn deflate(data: Bytes) -> Bytes— zlib-compressed (the HTTP "deflate" format).static fn deflate(data: Bytes, level: int) -> Bytes— zlib at a level from 0 to 9.static fn deflateRaw(data: Bytes) -> Bytes— Raw deflate, with no header or checksum (as in zip files).static fn inflate(data: Bytes) -> Bytes— The bytes of zlib (or gzip) data.static fn inflateRaw(data: Bytes) -> Bytes— The bytes of raw deflate data.static fn decompress(data: Bytes, maxBytes: int) -> Bytes— Decompresses gzip, zlib or raw deflate data (whichever it is), producing at mostmaxBytesbytes (ValueError beyond that).static fn gzipText(text: string) -> Bytes— Text gzip-compressed.static fn gunzipText(data: Bytes) -> string— gzip data decompressed to text.static fn isGzip(data: Bytes) -> bool— Whether the data starts like gzip (1f 8b).static fn isZlib(data: Bytes) -> bool— Whether the data starts like a zlib stream.
class GzipWriter
gzip written a piece at a time: each write hands the compressed output made so far to the sink (or the file), so nothing needs to fit in memory.
let gz = GzipWriter.toFile("backup.tar.gz") gz.write(chunk); ...; gz.finish() // finish() writes the end
Constructors
new GzipWriter(sink: fn(Bytes), level: int = 6)— Compressed output goes tosink, in pieces, as it is made.
Static members
static fn toFile(path: string, level: int = 6) -> GzipWriter— Compressed output to the file atpath(replaced); IOError when it cannot be opened.
Fields
bytesIn: long = 0— Bytes given to write, and compressed bytes handed on.bytesOut: long = 0
Methods
fn write(data: Bytes) -> GzipWriterfn writeString(text: string) -> GzipWriterfn finish()— Ends the stream (writing its trailer) and closes the file; once.
class GzipReader
gzip read a piece at a time: compressed input comes from the source (or the file) as needed, and read() gives up to max bytes of the original. Members written one after another read as one stream.
let gz = GzipReader.fromFile("backup.tar.gz") while (true) { let part = gz.read(65536); if (part.isEmpty()) { break }; ... }
Constructors
new GzipReader(source: fn(int) -> Bytes)— Compressed input is asked ofsource(up to the number of bytes given; an empty result means there is no more).
Static members
static fn fromFile(path: string) -> GzipReader— Reads the gzip file atpath; IOError when it cannot be opened.
Methods
fn read(max: int = 65536) -> Bytes— Up tomaxbytes of the original; empty at the end. ValueError on bad data.fn readAll() -> Bytes— Everything left, at once.