gzip
Compressing and decompressing data in the gzip format (zlib), for files ending in .gz and HTTP bodies with Content-Encoding: gzip.
Data goes in and out as Str, which may hold any bytes. Compressing cannot fail. Decompressing returns Str ! GzipError: the input may be damaged, cut short, or not gzip at all.
Compress and get the data back:
import gzip
let text = "line\n".repeat(1000)let packed = gzip.compress(&text)print(packed.len() < 100)let back = try gzip.decompress(&packed)print(back == text)truetrueWrite a .gz file and read it again:
import fsimport gzip
let dir = try fs.temp_dir()let path = dir.join(&"notes.txt.gz")try fs.write(&path, &gzip.compress(&"remember the milk\n"))let packed = try fs.read(&path)print(try gzip.decompress(&packed))remember the milkHandle input that is not gzip:
import gzip
let text = gzip.decompress(&"plain text") catch { gzip.GzipError(e) => { print(e.message) "" }}print(text.len())incorrect header check0Reference
Section titled “Reference”import gzipFunctions
Section titled “Functions”compress
Section titled “compress”pub fn compress(data: &Str) -> StrGzip at the default level (6).
compress_with
Section titled “compress_with”pub fn compress_with(data: &Str, level: i64) -> StrGzip at level 1 (fastest) to 9 (smallest).
level must be 1 to 9; any other value panics, because it is a mistake in the program rather than in the data. Level 1 is fastest, 9 gives the smallest output, and compress uses 6.
decompress
Section titled “decompress”pub fn decompress(data: &Str) -> Str ! GzipErrorGzip or zlib data back to bytes, refusing to grow past 256 MB.
Reads both gzip and zlib data (the header tells which). Raw deflate data without a header is not accepted.
A small compressed input can expand to gigabytes (a “zip bomb”). decompress stops with a GzipError once the result would pass 256 MB. When the data comes from outside, set a tighter limit with decompress_limited.
Several gzip members one after another (as cat a.gz b.gz makes) are read as one file, as RFC 1952 says. Anything else after the end of the compressed data is an error, not silently ignored.
decompress_limited
Section titled “decompress_limited”pub fn decompress_limited(data: &Str, max: i64) -> Str ! GzipErrorLike decompress, with the largest result accepted.
max is the largest decompressed size accepted, in bytes. Larger results are an error, not a truncated result:
import gzip
let packed = gzip.compress(&"x".repeat(10000))let small = gzip.decompress_limited(&packed, 1000) catch { gzip.GzipError(e) => e.message}print(small)the data grows past the size limitGzipError
Section titled “GzipError”pub struct GzipError { pub message: Str}