brotli

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

    brotli
    compression
    decompression
    encoder
    rfc7932
    streaming
    Download zip
    Author
    Version
    0.6.0
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    6K

    #gaato/brotli

    Brotli (RFC 7932) compression and decompression in pure MoonBit, for Native, JS, Wasm and Wasm GC. Use it for an HTTP client's or server's br content coding, or to compress static files ahead of time at the highest quality.

    The decoder and the encoder take input in chunks of any size and write into output buffers you choose. Their memory bounds can be queried before you make one. Both implement gaato/codec_bytes, so the same loop drives gzip, Zstandard and the other codecs of codecs.mbt.

    #Install

    moon add gaato/brotli

    #Compress and decompress bytes

    ///|
    test "compress and decompress" {
    let text = b"hello, hello, hello, brotli"
    let compressed = @brotli.compress(text) // quality 4
    assert_eq(@brotli.decompress(compressed), text)
    }

    ///|
    test "decompress with an output cap" {
    let compressed = b"\x0b\x02\x80hello\x03" // compress(b"hello")
    let text = @brotli.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.

    #Decode a stream as it arrives

    Keep one Decoder for the stream. Advance the input by last_consumed(), take last_produced() bytes of output, and pass end=true once the source has run dry, with an empty input if need be, so that a stream cut short, or a source with nothing in it, 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 = @brotli.Decoder()
    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"\x0b\x02", b"\x80hel", b"lo\x03"]), bytes => {
    decoded.write_bytes(bytes)
    })
    assert_eq(decoded.to_bytes(), b"hello")
    }

    Brotli has no framing, so an input holds one stream. To read a stream followed by data of your own, make the decoder with until=EndOfMember. It stops right after the stream, and input[decoder.last_consumed():] is what follows.

    #Encode a stream

    Flush makes the output so far decodable, say to send one part of an HTTP response. Finish ends the stream. A flush with nothing new since the last one writes nothing. The encoder never raises.

    ///|
    /// Compresses each part `read` hands over and flushes it, so that the output
    /// so far decodes in full; at `None` it finishes the stream, which an empty
    /// source needs too.
    fn encode_parts(read : () -> Bytes?, write : (Bytes) -> Unit) -> Unit {
    let encoder = @brotli.Encoder()
    let out = FixedArray::make(64 * 1024, b'\x00')
    for ;; {
    let piece = read()
    let action : @brotli.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 = @brotli.decompress(encoded.to_bytes())
    assert_eq(decoded, b"<html><body>hello</body></html>")
    }

    The output depends only on the input, the options and where Flush falls, never on how the input or output is split.

    #Choosing a quality

    QualityWhat it doesTypical use
    0–1Fast fragment encodersResponses compressed on the fly where CPU matters most
    2–3Simple hashers, greedy parsing
    4 (default)Lazy LZ77, one prefix code per meta-blockGeneral use
    5–9Block splitting and context models
    10–11Binary-tree matching and cost-based parsing: much slower, smallest outputStatic assets compressed once

    Qualities 0–3 and 5–11 follow the reference encoder. Values outside 0–11 are clamped. When you stream with Encoder and know the input length, pass size_hint=n to get the same bytes compress would write. The encoding notes give sizes and speeds per quality.

    #Defaults and limits

    OptionDefaultNotes
    quality (compress, Encoder)40 to 11.
    window_bits (compress, Encoder)22 (4 MiB)Clamped to 10–24.
    max_window_bits (decompress, Decoder)24 (16 MiB, Brotli's largest)A stream that needs a larger window raises LimitExceeded.
    max_output (decompress)noneRaises LimitExceeded with resource: Output past it.
    until (Decoder)EndOfInput

    A decoder holds its window, which is never more than the output so far, plus at most 1.3 MiB of tables. decoder_memory_bound(max_window_bits~) gives the bound before you make one. encoder_memory_bound(quality~, window_bits~, size_hint?) bounds an encoder, and compress_bound(n, quality~, window_bits~) bounds the output. memory_usage() reports the current amount on either. Resource bounds lists every limit.

    #Dictionaries

    An LZ77 dictionary of raw bytes (RFC 9841 section 3.2), given as a Dictionary to Decoder, Encoder, compress or decompress, lets a stream copy from it. brotli -D writes such streams, and RFC 9842's dcb coding uses them. The rest of Shared Brotli (serialized shared dictionaries, the large window and its framing) is not included, and a large-window stream raises Corrupt.

    #Errors

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

    KindWhen
    TruncatedThe input ends inside the stream.
    CorruptThe input is not a valid stream, or a copy runs past the end of the dictionary.
    TrailingDataBytes follow the stream (with the default EndOfInput).
    LimitExceededA window over max_window_bits (resource: Memory), or more than max_output from decompress (resource: Output).

    A step that raises first hands out the output that comes before the error. Errors stick: every later step raises the same kind until reset().

    #License

    Apache-2.0, with the quality 5..11 encoder port from google/brotli under MIT (LICENSE-encoder). The static dictionary in src/static_data.mbt is also MIT; see LICENSE-dictionary.

    EncodeAction

    Status and EncodeAction are gaato/codec_bytes's: a step answers Done, NeedMoreInput or NeedMoreOutput, and an encoder's step is told to Continue, Flush or Finish. Errors are gaato/codec's CodecError(kind, message).

    Status

    using @gaato/codec_bytes { type Status }

    Status and EncodeAction are gaato/codec_bytes's: a step answers Done, NeedMoreInput or NeedMoreOutput, and an encoder's step is told to Continue, Flush or Finish. Errors are gaato/codec's CodecError(kind, message).

    Decoder

    pub struct Decoder {
    // private fields
    }

    A streaming Brotli decoder (RFC 7932). Feed it input in chunks of any size with step and collect output in slices of any size; it keeps the sliding window (at most 16 MiB, and no more than the output so far) plus 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 a stream whose window exceeds what max_window_bits allows: LimitExceeded with the Memory resource, where needed is the stream's window and limit the largest one allowed, both (1 << WBITS) - 16 bytes (RFC 7932 section 9.1). The default 24 accepts every RFC 7932 stream. Values are clamped to 10..24.

    Brotli has no framing: an input holds one stream. With until at its default EndOfInput, bytes after the stream raise TrailingData; with EndOfMember, step answers Done right after the stream's last meta-block and consumes nothing past it, so input[last_consumed():] is what follows the stream.

    With dictionary, the stream may copy from it as RFC 9841 section 3.2 has it, as RFC 9842's dcb coding does: distances just past the window's reach (the output so far, or the window once it is full) address the dictionary from its end, and the static dictionary's words come after them. A copy that would run past the dictionary's end raises Corrupt, as the reference decoder (google/brotli) refuses it: RFC 9841 has it go on into the window, which a full window no longer holds. 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 and the prefix code tables of the largest meta-block so far, which grow with the stream, and what is allocated with the decoder (the context maps, the trees' offsets, the code reader's and the table builder's scratch space), 27,793 bytes. At most 1 << max_window_bits plus 1,343,596 bytes of tables plus those (see RESOURCE_BOUNDS.md). reset releases the window and keeps the tables. The static dictionary, shared by every decoder, and an LZ77 dictionary, the caller's bytes kept by reference, are not counted.

    Decoder::reset

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

    Starts a new stream, keeping the tables' memory. The window is 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. end says whether input holds the last bytes there are: then a stream cut short raises Truncated instead of asking for more. With EndOfInput, Done comes once the stream has ended, end is true and every byte is consumed; bytes after the end of the stream raise TrailingData. With EndOfMember, Done comes once the stream has ended, and the bytes after it are left unconsumed.

    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 of raw bytes for Decoder and Encoder, held by reference (the bytes it is a view of stay alive as long as it does).

    Dictionary::Dictionary

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

    A dictionary of content, as RFC 9841 section 3.2 calls an LZ77 dictionary and brotli -D takes one.

    Dictionary::content

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

    The dictionary's bytes.

    Dictionary::length

    fn Dictionary::length(self : Dictionary) -> Int

    The dictionary's length in bytes.

    Dictionary::memory_usage

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

    Bytes the dictionary holds of its own: once an encoder has used it, the index encoders search it with, shared by every encoder given it: a copy of the dictionary's last 64 MiB at most (the part a distance can reach), four bytes per byte of that, and a table of at most 512 KiB. Its content is the caller's and not counted.

    Encoder

    pub struct Encoder {
    // private fields
    }

    A streaming Brotli encoder (RFC 7932). Quality 4 uses lazy LZ77 and one prefix code per category. Qualities 0..1 use reference fragment encoders, 2..3 simple hashers and greedy parsing. Qualities 5..9 use the reference's hashers, static dictionary and context modelling; 10..11 use a binary tree and cost-based parsing with histogram clustering. Input and output chunks may have any size; memory stays within encoder_memory_bound.
    impl Encode for Encoder

    Encoder::Encoder

    fn Encoder::Encoder(quality? : Int, size_hint? : Int64, window_bits? : Int, dictionary? : Dictionary) -> Encoder

    An encoder at the start of a stream, with a window of 1 << window_bits bytes (clamped to 10..24). The default 22 is the reference encoder's; a decoder needs up to that much memory. quality defaults to 4 and is clamped to 0..11. Qualities 0..3 and 5..11 follow brotli 1.2.1; 4 retains gaato's lazy encoder and its pins.

    size_hint steers parameter selection at qualities 5..9. It is not written to the stream or checked: a wrong hint still produces valid output, which may differ. It is clamped to 0..1 GiB; zero, like an omitted hint, uses the reference CLI's stdin mode. With a positive known size, output matches its named-file mode at the same window. Without a hint, input is processed on a fixed 512 KiB read schedule, independent of caller chunks. Quality 4 ignores the hint. Qualities 0..3 and 10..11 make the same choices with either hint mode. At qualities 0..1 the declared window is at least 18 bits, as in the reference; the requested window still limits each fragment's input.

    With dictionary, a match may copy from it as RFC 9841 section 3.2 has it, as brotli -D writes and RFC 9842's dcb coding reads: at a distance past the window's reach, however far into the stream. A decoder needs the same dictionary. The dictionary keeps the index the encoder searches it with, built the first time and shared by every encoder given it (Dictionary::memory_usage). As in brotli 1.2.1, qualities 0..3 do not search the raw dictionary; quality 2 still accounts for it when addressing static dictionary words.

    Encoder::is_finished

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

    Whether the stream 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.

    Encoder::memory_usage

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

    Bytes in owned input and output buffers, hash tables, retained commands and coding tables; runtime object headers and garbage collection are excluded. encoder_memory_bound bounds these buffers and coding scratch before construction (see RESOURCE_BOUNDS.md). reset releases input. A dictionary's index is shared by the encoders given it and counted by Dictionary::memory_usage, not here. At qualities 5..11 this also counts the read buffer, retained commands, reference search tables (including H10's forest) and the ring used after the first window wrap; encoder_memory_bound includes their worst case and coding scratch.

    Encoder::reset

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

    Starts a new stream with the same quality, window, dictionary and hint. Releases input and reference-matcher buffers; quality 4 keeps its tables.

    Encoder::step

    fn Encoder::step(self : Encoder, input : BytesView, output : MutArrayView[Byte], action~ :
    EncodeAction
    ) ->
    Status

    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 compresses everything buffered and pads to a byte boundary, so that the output so far decodes to the input so far, and Finish ends the stream. Both stay in effect while the step answers NeedMoreOutput. Status: NeedMoreInput once everything is taken and its output handed out (a Flush is then complete), NeedMoreOutput while output waits, Done once the stream has ended and been handed out; after that, steps take no input and answer Done.

    Encoder::step_into

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

    step into a whole FixedArray, with bulk copies.

    compress

    fn compress(input : BytesView, quality? : Int, window_bits? : Int, dictionary? : Dictionary) -> Bytes

    Compresses input into a whole Brotli stream. window_bits is as for Encoder. At quality 4 the window declared is reduced to what the input needs (at least 64 KiB), preserving its default output. Other qualities pass the input length as size_hint and follow Encoder's window rules, so an Encoder given that hint and window produces the same stream. quality and dictionary are as for Encoder.

    compress_bound

    fn compress_bound(n : Int64, quality? : Int, window_bits? : Int) -> Int64

    The most bytes compress writes for n bytes of input at the given quality and window (clamped as by Encoder). Defaults preserve the quality-4 bound. Qualities 0..1 use fragments of min(window, 512 KiB), 2..3 use 16 KiB input blocks, and the remaining qualities use a conservative 64 KiB unit. Each unit needs its bytes and 5 more, since a meta-block that would come out larger than its bytes is written uncompressed (4 header bytes) and the last one then needs an empty last meta-block after it. An Encoder's stream of n bytes is within it too, plus 7 bytes for each Flush (the meta-block it ends, and the empty metadata block that pads it to a byte). 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..24, as Decoder clamps it): the window, the prefix code tables of the largest meta-block a stream may declare (1,343,596 bytes) and the 27,793 bytes allocated with the decoder. The static dictionary is shared and an LZ77 dictionary is the caller's, so neither is counted.

    decompress

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

    Decodes a whole Brotli stream held in memory. 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(window_bits? : Int, quality? : Int, size_hint? : Int64) -> Int64

    The most Encoder::memory_usage reports for an encoder made with window_bits (clamped to 10..24, as Encoder clamps it): its input buffer at its largest, twice the most output that waits (the buffer doubles), and what it allocates when it is made. A dictionary's index is counted by Dictionary::memory_usage, not here. quality and size_hint follow Encoder; a hint can select larger hash tables at qualities 5 and 6. The reference path also reserves for delayed commands, a 512 KiB read buffer, the reference ring, output and 8 MiB of histogram and Huffman scratch. The bound is computed without allocating these buffers. Qualities 10..11 instead derive their scratch bound from the H10 forest, packed cost nodes, match archive, block partitions and clustering queues. The hint does not change their bound. This worst-case bound includes pathological block partitions; typical retained memory is much smaller. Qualities 0..1 bound fragment input, rewrite storage, hash and program buffers; 2..3 bound their simple hashers, delayed commands and coding buffers. Their hints do not affect allocation. RESOURCE_BOUNDS.md derives each quality's formula and lists the backing tests.