Streaming DEFLATE, zlib and gzip decoders and encoders (RFC 1951, 1950, 1952) for MoonBit: arbitrary input chunks, bounded output slices, checksums verified, gzip headers and members, zlib preset dictionaries, levels 0 to 12 and sync flush.
moon add gaato/deflate| Package | Format | Use it for |
|---|---|---|
| gaato/deflate | raw DEFLATE | ZIP method 8, WebSocket permessage-deflate, formats that frame DEFLATE themselves |
| gaato/deflate/zlib | zlib | HTTP's deflate coding, PNG image data, Discord's zlib-stream |
| gaato/deflate/gzip | gzip | .gz files, HTTP's gzip coding |
| gaato/deflate/deflate64 | Deflate64, decode only | ZIP method 9 entries |
///|
test "compress and decompress a whole stream of each format" {
let text = b"hello, hello, hello"
assert_eq(@deflate.decompress(@deflate.compress(text)), text)
assert_eq(@zlib.decompress(@zlib.compress(text, level=9)), text)
assert_eq(@gzip.decompress(@gzip.compress(text, level=1)), text)
}
///|
test "decompress with a cap on the output" {
let gzip = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\x03\xcb\x48\xcd\xc9\xc9\x07\x00\x86\xa6\x10\x36\x05\x00\x00\x00"
assert_eq(@gzip.decompress(gzip, max_output=16 * 1024 * 1024), b"hello")
}///|
/// Decodes a gzip stream that `read` hands over in pieces, `None` once it has
/// no more, and passes the output to `write` as it is decoded.
fn gunzip(read : () -> Bytes?, write : (Bytes) -> Unit) -> Unit raise {
let decoder = @gzip.Decoder()
let out = FixedArray::make(64 * 1024, b'\x00')
for ;; {
let piece = read()
let end = piece is None
let mut input = match piece {
Some(bytes) => bytes[:]
None => b""[:]
}
for ;; {
let status = decoder.step_into(input, out, end~)
input = input[decoder.last_consumed():]
write(Bytes::from_array(out[:decoder.last_produced()]))
match status {
Done => return
NeedMoreInput => break
NeedMoreOutput => ()
}
}
}
}
///|
test "decode a gzip stream that arrives in pieces" {
let pieces = [
b"\x1f\x8b\x08\x00\x00\x00\x00\x00", b"\x02\x03\xcb\x48\xcd\xc9\xc9\x07", b"\x00\x86\xa6\x10\x36\x05\x00\x00\x00",
]
let mut next = 0
let decoded = Buffer()
gunzip(
() => {
if next < pieces.length() {
next += 1
Some(pieces[next - 1])
} else {
None
}
},
bytes => decoded.write_bytes(bytes),
)
assert_eq(decoded.to_bytes(), b"hello")
// A source with nothing in it is a stream cut short, not an empty one.
let empty = try gunzip(() => None, _ => ()) catch {
@codec_bytes.CodecError::CodecError(kind, _) => Some(kind)
_ => None
} noraise {
_ => None
}
assert_true(empty is Some(Truncated))
}///|
/// Steps `encoder` over `input` with `action`, passing each piece of output
/// to `write`, until all of `input` is taken and, for `Finish`, the stream
/// has ended.
fn encode(
encoder : @zlib.Encoder,
input : BytesView,
action : @zlib.EncodeAction,
out : FixedArray[Byte],
write : (Bytes) -> Unit,
) -> Unit {
let mut input = input
for ;; {
let status = encoder.step_into(input, out, action~)
input = input[encoder.last_consumed():]
write(Bytes::from_array(out[:encoder.last_produced()]))
if status is (NeedMoreInput | Done) {
break
}
}
}
///|
test "flush after each message, then finish the stream" {
let encoder = @zlib.Encoder()
let decoder = @zlib.Decoder(until=EndOfMember)
let out = FixedArray::make(64 * 1024, b'\x00')
let decoded = FixedArray::make(64 * 1024, b'\x00')
let stream = Buffer()
for message in [b"{\"op\":10}", b"{\"op\":11}"] {
let part = Buffer()
encode(encoder, message, Flush, out, bytes => part.write_bytes(bytes))
let part = part.to_bytes()
// A flushed part ends in 00 00 ff ff, and decodes in full on arrival.
assert_true(part is [.., 0x00, 0x00, 0xff, 0xff])
assert_true(decoder.step_into(part, decoded, end=false) is NeedMoreInput)
assert_eq(Bytes::from_array(decoded[:decoder.last_produced()]), message)
stream.write_bytes(part)
}
encode(encoder, b"", Finish, out, bytes => stream.write_bytes(bytes))
assert_eq(@zlib.decompress(stream.to_bytes()), b"{\"op\":10}{\"op\":11}")
}| Option | Taken by | Default | Meaning |
|---|---|---|---|
| level | compress, Encoder | 6 | 0 stores, 1 is the fastest, 12 the smallest. -1, zlib's Z_DEFAULT_COMPRESSION, means 6; other values outside 0 to 12 are clamped. The levels follow libdeflate's: 10 to 12 search much harder and hold far more memory. |
| window_bits | raw and zlib compress, Encoder | 15 (32 KiB) | 8 to 15, clamped. No match reaches further back than 1 << window_bits bytes, for a peer that keeps less history, as WebSocket's server_max_window_bits and client_max_window_bits negotiate. A zlib header's CINFO says it. |
| dictionary | raw and zlib compress, decompress, Encoder, Decoder | none | A preset dictionary; see zlib. |
| max_output | every decompress | none | A cap on the decoded size; a negative one counts as 0. |
| until | every Decoder | EndOfInput | EndOfMember stops right after the first stream or gzip member and consumes nothing past it. |
| keep_header | @gzip.Decoder | true | false skips each header's extra field, name and comment, whatever their size; see gzip. |
| max_header_bytes | @gzip.Decoder | 65,536 | The most a header's extra field, name and comment may hold between them. |
| header | @gzip.compress, @gzip.Encoder | none | The member's header; see gzip. |
| Holds | |
|---|---|
| Raw or zlib decoder | 46,592 bytes, from its first step to its last |
| gzip decoder | the same, plus the current header's fields up to max_header_bytes (none with keep_header=false) |
| Deflate64 decoder | 79,384 bytes |
| Encoder, levels 5 to 9 | 542,516 bytes; less at lower levels |
| Encoder, levels 10 to 12 | up to 7,056,748 bytes |
///|
test "a stream that needs a dictionary" {
let dictionary = b"hello, dictionary"
// zlib.deflateSync("hello", { dictionary }) in Node.
let stream = b"\x78\xbb\x39\x4e\x06\x97\xcb\x00\x09\x00\x00\x06\x2c\x02\x15"
let needed = try @zlib.decompress(stream) catch {
CodecError(DictionaryRequired(id), _) => id
_ => None
} noraise {
_ => None
}
assert_eq(needed, Some(@zlib.dictionary_id(dictionary)))
assert_eq(@zlib.decompress(stream, dictionary~), b"hello")
}///|
test "decode a Deflate64 entry with a match longer than DEFLATE allows" {
let entry = b"\x4b\x1c\xfd\xff\x07\x00"
assert_eq(
@deflate64.decompress(entry, max_output=1 << 20),
Bytes::make(65539, b'a'),
)
}| Kind | When |
|---|---|
| Truncated | The input ends inside a stream, or holds none. |
| Corrupt | The input is not a valid stream: reserved block types or header values, bad Huffman codes, a distance before the start of the output. |
| ChecksumMismatch | An Adler-32, a CRC-32, a gzip length or a gzip header CRC does not match. |
| TrailingData | Bytes follow the stream; for gzip, bytes that begin no other member. |
| DictionaryRequired(Some(id)), DictionaryMismatch | A zlib stream names a preset dictionary that was not given, or another one was. |
| LimitExceeded | Output past max_output (resource: Output), or a gzip header's fields past max_header_bytes (resource: Memory). |
pub struct Decoder {
// private fields
}fn step(self : Decoder, input : BytesView, output : MutArrayView[Byte], end~ : Bool) -> Status raise CodecErrorfn Decoder::step(self : Decoder, input : BytesView, output : MutArrayView[Byte], end~ : Bool) -> Status raise CodecErrorfn Decoder::step_into(self : Decoder, input : BytesView, output : FixedArray[Byte], end~ : Bool) -> Status raise CodecErrorpub struct Encoder {
// private fields
}fn step(self : Encoder, input : BytesView, output : MutArrayView[Byte], action~ : EncodeAction) -> Status raise CodecErrorfn Encoder::step(self : Encoder, input : BytesView, output : MutArrayView[Byte], action~ : EncodeAction) -> Statusfn Encoder::step_into(self : Encoder, input : BytesView, output : FixedArray[Byte], action~ : EncodeAction) -> Statusfn compress(input : BytesView, level? : Int, dictionary? : BytesView, window_bits? : Int) -> Bytesfn compress_bound(n : Int64) -> Int64fn decoder_memory_bound() -> Int64fn decompress(input : BytesView, dictionary? : BytesView, max_output? : Int) -> Bytes raise CodecErrorfn encoder_memory_bound(level? : Int) -> Int64Install
Download zipStreaming DEFLATE, zlib and gzip decoders and encoders (RFC 1951, 1950, 1952) for MoonBit: arbitrary input chunks, bounded output slices, checksums verified, gzip headers and members, zlib preset dictionaries, levels 0 to 12 and sync flush.