zstd

    A streaming Zstandard (RFC 8878) decoder and encoder in pure MoonBit: arbitrary input chunks, bounded output slices, memory bounded by the window.

    zstd
    zstandard
    compression
    decompression
    rfc8878
    streaming
    Download zip
    Author
    Version
    0.6.1
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    6K

    #gaato/zstd

    Zstandard (RFC 8878) compression and decompression in pure MoonBit, for Native, JS, Wasm and Wasm GC. Use it to decode an HTTP zstd response as it arrives, to compress a file or a response, or to cut a stream into frames without decoding it.

    The decoder and the encoder take input in chunks of any size and write into output buffers you choose. The decoder's window is bounded by the max_window_bits you allow, its other memory by about 270 KiB, and it allocates nothing because of a size a header claims. Both implement gaato/codec_bytes, so the same loop drives gzip, Brotli and the other codecs of codecs.mbt.

    #Install

    moon add gaato/zstd

    #Compress and decompress bytes

    ///|
    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")
    }

    decompress has no output cap unless you pass max_output. Set one for input that comes from elsewhere: a few bytes of zstd can expand to gigabytes.

    #Decode a stream as it arrives

    Feed input as it comes, and take output in slices of the size you choose. A stream may hold several frames and nothing marks the last one, so every step says whether the source has run dry: end=false while it has more, end=true once it has none, with an empty input if need be. A stream cut short, or a source with nothing in it, then raises Truncated.

    ///|
    /// 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")
    }

    A Decoder's memory is bounded by its window, but its total output is not. For input from elsewhere, count what write receives and stop past your budget.

    To read one frame followed by something else, make the decoder with until=EndOfMember. It stops right after the first frame and consumes nothing past it, so what follows is input[decoder.last_consumed():].

    #Encode a stream

    Encoder works the same way, with an action in place of end. Flush makes the output so far decodable, say to send one part of an HTTP response. Finish ends the frame. A flush costs a 3-byte block header. A flush with nothing new since the last one writes nothing.

    ///|
    /// 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>")
    }

    The frame's bytes depend only on the input, the options and where Flush falls, never on how the input or output is split.

    #Defaults and limits

    OptionDefaultNotes
    level (compress, Encoder)31 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)trueWrites the XXH64 content checksum. The decoder checks it when present.
    content_size (Encoder)unknownGive 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)noneRaises LimitExceeded with resource: Output past it.
    until (Decoder)EndOfInputDecodes every frame. EndOfMember stops after the first.

    A decoder holds at most 2^max_window_bits bytes plus 256 KiB for a block, plus 13 KiB of tables. decoder_memory_bound(max_window_bits=n) gives that bound before you make one, and memory_usage() reports the current amount. For input of unknown size, an encoder holds about 3.1 MiB at level 1, 6.8 MiB at level 3 and 50 MiB at level 12. encoder_memory_bound(level~, content_size?) gives the bound for any level. compress_bound(n) is the most compress writes for n bytes.

    #Dictionaries

    Pass a Dictionary to Decoder, Encoder, compress or decompress. Dictionary::parse(bytes) reads a dictionary in the format zstd --train writes, and Dictionary::raw(bytes) takes plain content, as RFC 9842's dcz coding does. Frames made with zstd -D decode, and frames written here decode with zstd -d -D. Training dictionaries is not included.

    #Read frames without decoding them

    inspect_frame reads the header of the frame at the start of some bytes. frame_size walks the block headers to where the frame ends, so you can cut a stream into frames, or check that a frame is whole, cheaply. skippable_frame and read_skippable_frame write and read frames that carry your own bytes, which every decoder skips.

    ///|
    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")
    }

    #Errors

    A malformed stream raises gaato/codec's CodecError(kind, message). The decoder never aborts on bad input.

    KindWhen
    TruncatedThe input ends inside a frame.
    CorruptThe input is not a valid stream.
    TrailingDataBytes after the last frame start no frame.
    ChecksumMismatchThe content checksum does not match. The encoder also raises it when the input does not match the content_size it was given.
    LimitExceededA 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.
    DictionaryMismatchThe frame names a different dictionary from the one given.

    A step that raises first hands out the output that comes before the error, so a streaming caller may already hold bytes when the checksum at the end fails. Errors stick: every later step raises the same kind until reset().

    In a catch, CodecError(kind, _) and the kinds match unqualified. To name the types elsewhere, import gaato/codec_bytes, which re-exports them.

    #Not included

    Long-distance matching, multithreaded compression and dictionary training.

    #License

    Apache-2.0. The test frames under testdata/upstream come from facebook/zstd under its BSD license; see NOTICE.

    EncodeAction

    What Encoder::step does once its input is taken: Continue, Flush or Finish, as every gaato/codec_bytes encoder takes it.

    Status

    using @gaato/codec_bytes { type Status }

    Outcome of one Decoder::step or Encoder::step: Done, NeedMoreInput or NeedMoreOutput, as every gaato/codec_bytes codec answers.

    Decoder

    pub struct Decoder {
    // private fields
    }

    A streaming Zstandard decoder (RFC 8878). Feed it input in chunks of any size with step and collect output in slices of any size; it keeps the window (no more than a frame's Window_Size, and no more than its output so far), one compressed block and fixed-size tables, never the whole input or output.
    impl Decode for Decoder

    Decoder::Decoder

    fn Decoder::Decoder(max_window_bits? : Int, until? :
    Until
    , dictionary? : Dictionary) -> Decoder

    A decoder at the start of a stream. It refuses, with LimitExceeded({ resource: Memory, .. }), a frame whose Window_Size exceeds 1 << max_window_bits bytes (the window memory it would need). The default 27 is the reference decoder's default limit; RFC 9659 asks HTTP clients to accept 23 (8 MiB). Values are clamped to 10..30.

    until says where the stream ends. EndOfInput, the default, decodes every frame up to the end of the input. EndOfMember stops right after the first frame, a skippable frame included, and consumes nothing past it, so that input[last_consumed():] is what follows.

    dictionary is used by every frame that names it, or names none (RFC 8878 section 5): its content comes as if just before the frame's output, and a match may reach into it however long the frame is, as zstd's decoder lets it. A frame that names another dictionary raises DictionaryMismatch; without dictionary, a frame that names one raises DictionaryRequired(Some(id)). The decoder keeps the dictionary by reference, so the bytes it is a view of stay alive as long as the decoder, and memory_usage does not count them.

    Decoder::is_finished

    fn Decoder::is_finished(self : Decoder) -> Bool

    Whether the stream has ended and all its output has been handed out.

    Decoder::last_consumed

    fn Decoder::last_consumed(self : Decoder) -> Int

    Input bytes the latest step accepted: all of them on NeedMoreInput. A step that raised accepted the bytes up to the error; for TrailingData, exactly up to the end of the stream, or none if the stream ended before this step's input.

    Decoder::last_produced

    fn Decoder::last_produced(self : Decoder) -> Int

    Output bytes the latest step wrote, a step that raised included: the output before the error.

    Decoder::memory_usage

    fn Decoder::memory_usage(self : Decoder) -> Int

    Bytes the decoder holds: the window, the compressed block and its literals, which grow with the stream, and the Huffman and FSE tables and their scratch space, 13,156 bytes allocated with the decoder. At most (1 << max_window_bits) + 2 * 128 KiB plus those; the window is released when a frame needs a smaller one, so it may drop between frames. A dictionary is the caller's, kept by reference, and not counted; nor are the frame header being read and the checksum's state, under 100 bytes.

    Decoder::reset

    fn Decoder::reset(self : Decoder) -> Unit

    Starts a new stream with the same options, keeping the tables' memory. The window and the block buffers are released.

    Decoder::step

    fn Decoder::step(self : Decoder, input : BytesView, output : MutArrayView[Byte], end~ : Bool) ->
    Status
    raise
    CodecError

    Decodes from input into output; see last_consumed and last_produced for how much of each it used.

    A stream is one or more frames, and nothing marks its last one, so pass end=true once input holds the last bytes and end=false before: the stream then ends after the frame in progress, and a stream cut short raises Truncated. Without end, the decoder answers NeedMoreInput between frames. Bytes after the last frame that start no frame raise TrailingData. Under until=EndOfMember the stream ends after its first frame, whatever end says.

    An error comes after all the output before it: when output fills first, the step answers NeedMoreOutput and a later one hands out the rest and raises. After an error the decoder raises it again, consuming and writing nothing, until reset.

    Decoder::step_into

    fn Decoder::step_into(self : Decoder, input : BytesView, output : FixedArray[Byte], end~ : Bool) ->
    Status
    raise
    CodecError

    step into a whole FixedArray, with bulk copies.

    Dictionary

    pub struct Dictionary {
    // private fields
    }

    A dictionary for Decoder and Encoder: its content, held by reference (the bytes it is a view of stay alive as long as it does), and its id.

    Dictionary::content

    fn Dictionary::content(self : Dictionary) -> BytesView

    The content: the bytes that come before every frame's output.

    Dictionary::id

    fn Dictionary::id(self : Dictionary) -> UInt

    The id a frame names this dictionary by: 0 for raw content.

    Dictionary::is_formatted

    fn Dictionary::is_formatted(self : Dictionary) -> Bool

    Whether the dictionary is formatted: has entropy tables and repeat offsets of its own.

    Dictionary::parse

    fn Dictionary::parse(data : BytesView) -> Dictionary raise
    CodecError

    A dictionary from data, as zstd -D reads one: a formatted dictionary (RFC 8878 section 5, as zstd --train writes them) if it starts with the magic number 0xEC30A437, raw content otherwise. The content is a view of data.

    Raises Corrupt for a formatted dictionary whose entropy tables do not parse, whose repeat offsets are 0 or longer than its content, or that ends inside them.

    Dictionary::raw

    fn Dictionary::raw(content : BytesView) -> Dictionary

    A dictionary of raw content, content itself: its id is 0, so it is used for frames that name no dictionary, as RFC 8878 section 5 and zstd use one, and RFC 9842's dcz coding does.

    Encoder

    pub struct Encoder {
    // private fields
    }

    A streaming Zstandard encoder (RFC 8878). Feed it input in chunks of any size with step and collect output in slices of any size. It writes one frame: Raw, RLE or Compressed blocks of at most 128 KiB, whichever is smallest, and the XXH64 content checksum unless asked not to.

    Levels 1..22 select their size-class parameters. Levels 1..12 preserve their original fast/double-fast/greedy/lazy/lazy2 mapping; levels 13..22 use binary-tree lazy2 or optimal parsing.
    impl Encode for Encoder

    Encoder::Encoder

    fn Encoder::Encoder(level? : Int, checksum? : Bool, content_size? : Int64, dictionary? : Dictionary) -> Encoder

    An encoder at the start of a frame.

    level is zstd's compression level: 1 to 22, 3 by default as in zstd, and 0 is the default too; higher levels act as 22. The negative levels, -1 down to -131072 (lower ones act as that), are zstd's faster ones (zstd --fast=N is level -N): they skip ahead faster the lower they go, and leave literals uncoded, as zstd does.

    checksum adds the frame's content checksum, the low 32 bits of the XXH64 of the input, as zstd does by default.

    content_size, when given, is written in the frame header as Frame_Content_Size, and the input must then be exactly that long: step raises ChecksumMismatch once it has more, or at Finish when it has less. Like zstd, the encoder then picks its parameters from the size, and a frame that fits its window is written single-segment, so a decoder reserves no more than the content. A negative content_size counts as not given.

    dictionary comes before every frame, as zstd's -D puts it: the frame's matches may reach into it until the input is a window past it, and the parameters are chosen for the input and the dictionary together, as zstd chooses them. A decoder needs the same dictionary. The encoder keeps it by reference and copies its content into its history at the start of every frame, so its memory grows by the dictionary's length, twice: once for the dictionary and once for the room the history keeps beyond it.

    Encoder::is_finished

    fn Encoder::is_finished(self : Encoder) -> Bool

    Whether the frame has ended and all its output has been handed out.

    Encoder::last_consumed

    fn Encoder::last_consumed(self : Encoder) -> Int

    Input bytes the latest step took.

    Encoder::last_produced

    fn Encoder::last_produced(self : Encoder) -> Int

    Output bytes the latest step wrote, a step that raised included.

    Encoder::memory_usage

    fn Encoder::memory_usage(self : Encoder) -> Int

    Bytes the encoder holds in buffers that grow with the stream: the input block in shared history, the output waiting for the caller, match window and hash, sequence storage, and entropy coding scratch. Bounds for each are in RESOURCE_BOUNDS.md. reset keeps every buffer's capacity, so the count does not drop then; it stays within the bound of the encoder's options.

    Encoder::reset

    fn Encoder::reset(self : Encoder) -> Unit

    Starts a new frame with the same options, keeping the memory of its buffers and tables: the next frame's bytes are those a new encoder writes, and memory_usage still counts what is kept.

    Encoder::step

    Compresses from input into output; see last_consumed and last_produced for how much of each it used. Input that was not taken (when the output is full) must be passed again, with the same action.

    action applies once all of input is taken: Continue only takes input, Flush ends the block in progress, so that the output so far decodes to the input so far without ending the frame, and Finish ends the frame. Both stay in effect while the step answers NeedMoreOutput. A Flush with no input since the last one writes nothing. Status: NeedMoreInput once everything is taken and its output handed out (a Flush is then complete), NeedMoreOutput while output waits, Done once the frame has ended and been handed out; after that, steps take no input and answer Done.

    Raises only when the encoder was given content_size and the input does not match it: ChecksumMismatch, once the input passes it (the bytes up to it are taken as with Continue, and the output they decide is handed out first, so that the output before the error does not depend on how input and output are split) or at Finish when it falls short. The error sticks: later steps raise it again, taking and writing nothing, until reset.

    Encoder::step_into

    fn Encoder::step_into(self : Encoder, input : BytesView, output : FixedArray[Byte], action~ :
    EncodeAction
    ) ->
    Status
    raise
    CodecError

    step into a whole FixedArray, with bulk copies.

    Frame

    pub(all) enum Frame {
    Zstd(FrameInfo)
    Skippable(variant~ : Int, size~ : UInt)
    } derive(Eq,
    Debug
    )

    The frame at the start of some bytes, as inspect_frame sees it.

    Frame::equal

    fn Frame::equal(Frame, Frame) -> Bool

    Compares two frames read by inspect_frame, field by field.

    Frame::not_equal

    fn Frame::not_equal(x : Frame, y : Frame) -> Bool

    Compares two frames read by inspect_frame, field by field.

    Frame::to_repr

    Shows the frame as its fields, for tests and messages.

    FrameInfo

    pub struct FrameInfo {
    window_size : UInt64
    content_size : UInt64?
    dictionary_id : UInt
    has_checksum : Bool
    single_segment : Bool
    header_len : Int
    } derive(Eq,
    Debug
    )

    What a Zstandard frame's header says, as inspect_frame reads it.

    FrameInfo::equal

    fn FrameInfo::equal(FrameInfo, FrameInfo) -> Bool

    Compares two frame headers read by inspect_frame, field by field.

    FrameInfo::not_equal

    fn FrameInfo::not_equal(x : FrameInfo, y : FrameInfo) -> Bool

    Compares two frame headers read by inspect_frame, field by field.

    FrameInfo::to_repr

    Shows the frame header as its fields, for tests and messages.

    compress

    fn compress(input : BytesView, level? : Int, checksum? : Bool, dictionary? : Dictionary) -> Bytes

    Compresses input into one whole Zstandard frame. level, checksum and dictionary are as for Encoder; the frame states its content size, and the parameters are chosen for it, so a small input declares a small window (a single-segment frame, whose window is its content).

    compress_bound

    fn compress_bound(n : Int64) -> Int64

    The most bytes compress or an Encoder writes for n bytes of input, at any level and with any dictionary: the input, 3 bytes for each block (a block is never larger than its bytes stored raw, and is at least 1 KiB, the smallest window, unless it is the last), one block for no input, the magic number and the longest frame header (4 + 14, with a 4-byte dictionary id and an 8-byte content size) and the 4-byte checksum. Each Flush that ends a block early adds 3 bytes. Like ZSTD_compressBound, it allows for blocks smaller than compress writes (its blocks are 128 KiB once the input is), so that it holds for an Encoder whose parameters choose a small window. A negative n counts as 0; past 2^62 the result is the largest Int64.

    decoder_memory_bound

    fn decoder_memory_bound(max_window_bits? : Int) -> Int64

    The most Decoder::memory_usage reports for a decoder made with max_window_bits (clamped to 10..30, as Decoder clamps it): the window, a compressed block and its literals, and the 13,156 bytes of tables made with the decoder. A dictionary is the caller's and is not counted.

    decompress

    fn decompress(input : BytesView, max_output? : Int, max_window_bits? : Int, dictionary? : Dictionary) -> Bytes raise
    CodecError

    Decodes a whole Zstandard stream held in memory: one or more frames. max_output caps the decoded size (unlimited by default) and raises LimitExceeded({ resource: Output, .. }) past it, with max_output (0 for a negative one) as the limit; max_window_bits and dictionary are as for Decoder.

    encoder_memory_bound

    fn encoder_memory_bound(level? : Int, content_size? : Int64, dictionary_len? : Int) -> Int64

    The most Encoder::memory_usage reports for an encoder made with these options, whatever the input and however it is split: what the level's parameters (chosen for content_size and a dictionary of dictionary_len bytes, as Encoder chooses them) allocate, with the room its buffers may double into. level is as for Encoder.

    frame_size

    fn frame_size(input : BytesView) -> Int64 raise
    CodecError

    The length of the frame at the start of input, a Zstandard frame or a skippable one, found by reading its header and walking its block headers (an RLE block holds one byte, a raw or compressed block its size) and its checksum, without decoding anything; input[frame_size(input):] is what follows the frame. As zstd's ZSTD_findFrameCompressedSize.

    Raises Truncated if input ends inside the frame, and Corrupt for what inspect_frame refuses and for a block of the reserved type. The blocks' contents are not checked: Decoder does that.

    inspect_frame

    fn inspect_frame(input : BytesView) -> Frame raise
    CodecError

    Reads the header of the frame at the start of input without decoding it: a Zstandard frame's window, content size, dictionary and checksum flag, or a skippable frame's variant and size. Only the header's bytes are read.

    Raises Truncated if input ends inside the header, and Corrupt if it starts with neither magic number or the header's reserved bit is set. A window or a dictionary is not judged here: Decoder judges those.

    read_skippable_frame

    fn read_skippable_frame(input : BytesView) -> (Int, BytesView) raise
    CodecError

    The variant and the data of the skippable frame at the start of input, a view into input. Raises Truncated if input ends inside the frame, and Corrupt if it does not start with a skippable frame.

    skippable_frame

    fn skippable_frame(variant : Int, data : BytesView) -> Bytes

    A skippable frame of variant (its low four bits are used) holding data: the magic number 0x184D2A50 + variant, the length of data in four little-endian bytes, then data. Decoders skip it, so it carries bytes of the caller's beside Zstandard frames, as the header of RFC 9842's dcz coding does.