A streaming Zstandard (RFC 8878) decoder and encoder in pure MoonBit: arbitrary input chunks, bounded output slices, memory bounded by the window.
moon add gaato/zstd///|
test "compress and decompress" {
let text = b"hello, hello, hello, zstd"
let compressed = @zstd.compress(text) // level 3, as zstd's default
assert_eq(@zstd.decompress(compressed), text)
let smaller = @zstd.compress(text, level=12)
assert_eq(@zstd.decompress(smaller), text)
}
///|
test "decompress with an output cap" {
let compressed = b"\x28\xb5\x2f\xfd\x20\x05\x29\x00\x00\x68\x65\x6c\x6c\x6f" // compress(b"hello")
let text = @zstd.decompress(compressed, max_output=16 * 1024 * 1024)
assert_eq(text, b"hello")
}///|
/// Decodes what `read` hands over, `None` once it has no more, passing the
/// output to `write` as it is decoded.
fn decode_all(read : () -> Bytes?, write : (Bytes) -> Unit) -> Unit raise {
let decoder = @zstd.Decoder(max_window_bits=23) // 8 MiB, as RFC 9659 asks of HTTP
let out = FixedArray::make(64 * 1024, b'\x00')
for ;; {
let piece = read()
let end = piece is None
let mut input = piece.unwrap_or(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 => ()
}
}
}
}
///|
/// A source that hands over `pieces` one by one, then `None`.
fn pieces_of(pieces : Array[Bytes]) -> () -> Bytes? {
let mut next = 0
() => {
if next < pieces.length() {
next += 1
Some(pieces[next - 1])
} else {
None
}
}
}
///|
test "decode a stream chunk by chunk" {
let decoded = Buffer()
decode_all(
pieces_of([
b"\x28\xb5\x2f", b"\xfd\x20\x05\x29\x00\x00\x68", b"\x65\x6c\x6c\x6f",
]),
bytes => decoded.write_bytes(bytes),
)
assert_eq(decoded.to_bytes(), b"hello")
}///|
/// Compresses each part `read` hands over and flushes it, so that the output
/// so far decodes in full; at `None` it finishes the frame, which an empty
/// source needs too.
fn encode_parts(read : () -> Bytes?, write : (Bytes) -> Unit) -> Unit raise {
let encoder = @zstd.Encoder()
let out = FixedArray::make(64 * 1024, b'\x00')
for ;; {
let piece = read()
let action : @zstd.EncodeAction = if piece is None { Finish } else { Flush }
let mut input = piece.unwrap_or(b"")[:]
for ;; {
let status = encoder.step_into(input, out, action~)
input = input[encoder.last_consumed():]
write(Bytes::from_array(out[:encoder.last_produced()]))
match status {
Done => return
NeedMoreInput => break
NeedMoreOutput => ()
}
}
}
}
///|
test "encode a stream part by part" {
let encoded = Buffer()
encode_parts(pieces_of([b"<html>", b"<body>hello</body>", b"</html>"]), bytes => {
encoded.write_bytes(bytes)
})
let decoded = @zstd.decompress(encoded.to_bytes())
assert_eq(decoded, b"<html><body>hello</body></html>")
}| Option | Default | Notes |
|---|---|---|
| level (compress, Encoder) | 3 | 1 to 22, plus the fast levels -1 down to -131072 (zstd --fast=N is level -N). Higher levels search harder and use more memory. |
| checksum (compress, Encoder) | true | Writes the XXH64 content checksum. The decoder checks it when present. |
| content_size (Encoder) | unknown | Give it when known: it is written in the header, and the window and tables shrink to fit. |
| max_window_bits (decompress, Decoder) | 27 (128 MiB) | Frames that need a larger window are refused before anything is allocated. For HTTP, RFC 9659 asks for 23 (8 MiB). |
| max_output (decompress) | none | Raises LimitExceeded with resource: Output past it. |
| until (Decoder) | EndOfInput | Decodes every frame. EndOfMember stops after the first. |
///|
test "frames, read without decoding them" {
let note = @zstd.skippable_frame(3, b"made by me")
let frame = @zstd.compress(b"hello, hello, hello")
let stream = Bytes::from_array([..note[:], ..frame[:]])
assert_eq(@zstd.frame_size(stream), 18)
let rest = stream[18:]
guard @zstd.inspect_frame(rest) is Zstd(info) else { fail("not a frame") }
assert_eq(info.content_size, Some(19))
assert_eq(@zstd.read_skippable_frame(stream).1, b"made by me")
assert_eq(@zstd.decompress(stream), b"hello, hello, hello")
}| Kind | When |
|---|---|
| Truncated | The input ends inside a frame. |
| Corrupt | The input is not a valid stream. |
| TrailingData | Bytes after the last frame start no frame. |
| ChecksumMismatch | The content checksum does not match. The encoder also raises it when the input does not match the content_size it was given. |
| LimitExceeded | A window over max_window_bits (resource: Memory), or more than max_output from decompress (resource: Output). |
| DictionaryRequired(Some(id)) | The frame names a dictionary and none was given. |
| DictionaryMismatch | The frame names a different dictionary from the one given. |
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 Dictionary {
// private fields
}pub struct Encoder {
// private fields
}fn step(self : Encoder, input : BytesView, output : MutArrayView[Byte], action~ : EncodeAction) -> Status raise CodecErrorfn Encoder::Encoder(level? : Int, checksum? : Bool, content_size? : Int64, dictionary? : Dictionary) -> Encoderfn Encoder::step(self : Encoder, input : BytesView, output : MutArrayView[Byte], action~ : EncodeAction) -> Status raise CodecErrorfn Encoder::step_into(self : Encoder, input : BytesView, output : FixedArray[Byte], action~ : EncodeAction) -> Status raise CodecErrorfn compress_bound(n : Int64) -> Int64fn decoder_memory_bound(max_window_bits? : Int) -> Int64fn decompress(input : BytesView, max_output? : Int, max_window_bits? : Int, dictionary? : Dictionary) -> Bytes raise CodecErrorfn encoder_memory_bound(level? : Int, content_size? : Int64, dictionary_len? : Int) -> Int64fn skippable_frame(variant : Int, data : BytesView) -> BytesInstall
Download zipA streaming Zstandard (RFC 8878) decoder and encoder in pure MoonBit: arbitrary input chunks, bounded output slices, memory bounded by the window.