A streaming Brotli (RFC 7932) decoder and encoder in pure MoonBit: arbitrary input chunks, bounded output slices, memory bounded by the window.
moon add gaato/brotli///|
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")
}///|
/// 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")
}///|
/// 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>")
}| Quality | What it does | Typical use |
|---|---|---|
| 0–1 | Fast fragment encoders | Responses compressed on the fly where CPU matters most |
| 2–3 | Simple hashers, greedy parsing | |
| 4 (default) | Lazy LZ77, one prefix code per meta-block | General use |
| 5–9 | Block splitting and context models | |
| 10–11 | Binary-tree matching and cost-based parsing: much slower, smallest output | Static assets compressed once |
| Option | Default | Notes |
|---|---|---|
| quality (compress, Encoder) | 4 | 0 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) | none | Raises LimitExceeded with resource: Output past it. |
| until (Decoder) | EndOfInput |
| Kind | When |
|---|---|
| Truncated | The input ends inside the stream. |
| Corrupt | The input is not a valid stream, or a copy runs past the end of the dictionary. |
| TrailingData | Bytes follow the stream (with the default EndOfInput). |
| LimitExceeded | A window over max_window_bits (resource: Memory), or more than max_output from decompress (resource: Output). |
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(quality? : Int, size_hint? : Int64, window_bits? : Int, dictionary? : Dictionary) -> Encoderfn 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, quality? : Int, window_bits? : Int, dictionary? : Dictionary) -> Bytesfn compress_bound(n : Int64, quality? : Int, window_bits? : Int) -> 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(window_bits? : Int, quality? : Int, size_hint? : Int64) -> Int64Install
Download zipA streaming Brotli (RFC 7932) decoder and encoder in pure MoonBit: arbitrary input chunks, bounded output slices, memory bounded by the window.