lz4

    LZ4's frame and block formats: a streaming decoder and encoder for frames, with XXH32 checks, dictionaries, skippable and legacy frames.

    lz4
    compression
    streaming
    codec
    Download zip
    Author
    Version
    0.1.1
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    856

    #gaato/lz4

    LZ4 compression and decompression in pure MoonBit, for Native, JS, Wasm and Wasm GC. Use it to read and write .lz4 files and LZ4 frames from other programs, or to decode raw LZ4 blocks inside a container format that records their sizes.

    The frame decoder and encoder stream: they take input in chunks of any size, write into output buffers you choose, and check every checksum. With the same options and no dictionary, the encoder writes the bytes the reference lz4 1.10.0 writes. Both implement gaato/codec_bytes, so the same loop drives Zstandard, gzip and the other codecs of codecs.mbt.

    #Install

    moon add gaato/lz4

    #Frames or blocks

    An LZ4 frame (what the lz4 command writes) carries its own header, checksums and end. A block is bare compressed data: the program that stores it must also keep its decoded size, or a bound on it.

    ///|
    test "compress and decompress" {
    let text = b"hello, hello, hello, lz4"
    let frame = @lz4.compress(text)
    assert_eq(@lz4.decompress(frame, max_output=16 * 1024 * 1024), text)
    // A block on its own: the caller keeps its size, or a bound of it.
    let block = @lz4.compress_block(text)
    assert_eq(@lz4.decompress_block(block, max_output=text.length()), text)
    }

    ///|
    test "decode what lz4 wrote" {
    // `lz4` of "hello hello hello hello hello".
    let frame = b"\x04\x22\x4d\x18\x64\x40\xa7\x0f\x00\x00\x00\x6ehello \x06\x00\x50hello\x00\x00\x00\x00\x79\xb1\xff\xf9"
    assert_eq(@lz4.decompress(frame), b"hello hello hello hello hello")
    }

    decompress has no output cap unless you pass max_output. Set one for input that comes from elsewhere.

    #Decode frames as they arrive

    Pass end=true once the source has run dry, with an empty input if need be, so that a cut frame, or a source with nothing in it, raises Truncated. The decoder reads frames one after another, as lz4 -d does.

    ///|
    /// 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 = @lz4.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(input, out.mut_view(), 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 frame = @lz4.compress(b"one frame, then the next")
    let decoded = Buffer()
    let pieces = [frame[:9].to_owned(), frame[9:].to_owned(), frame]
    decode_all(pieces_of(pieces), bytes => decoded.write_bytes(bytes))
    assert_eq(
    decoded.to_bytes(),
    b"one frame, then the nextone frame, then the next",
    )
    }

    Decoder(until=EndOfMember) stops after the first frame and consumes nothing past it. Legacy frames (lz4 -l) end only where the next frame or the input does, so they raise Unsupported in that mode. frame_info() gives what the current frame's header says.

    Encoder() streams the other way, as the codec_bytes loop shows: Continue takes input, Flush writes what it holds as a block so the output so far decodes, and Finish ends the frame.

    #Defaults and limits

    OptionDefaultNotes
    acceleration1Higher is faster and larger. lz4 --fast=N is N + 1.
    block_sizeMax64KiBThe lz4 command uses Max4MiB with linked=false.
    linkedtrueBlocks may refer to the previous 64 KiB.
    checksumtrueContent checksum.
    block_checksumfalse
    content_sizenoneWritten in the header when given, and the input is held to it.
    max_output (decompress)noneRaises LimitExceeded past it.
    max_output (decompress_block)requiredA block does not say its size, so the caller gives its decoded size or a bound.

    The decoder holds at most 256 KiB (decoder_memory_bound()), never a whole block, however large the frame's blocks are. The encoder holds 229 KiB at the defaults and 8.1 MiB with 4 MiB blocks (encoder_memory_bound(block_size~)). compress_bound(n) bounds a frame and block_compress_bound(n) a block.

    #Dictionaries

    Decoder(dictionary=d) and decompress(dictionary=d) read frames written with lz4 -D. A frame that names a dictionary id in its header raises DictionaryRequired without one. Encoder(dictionary=…, dictionary_id=…) writes such frames. With a dictionary, the encoder's output differs slightly from the reference lz4, but both decode the same.

    #Errors

    A malformed frame raises gaato/codec's CodecError(kind, message). The decoders never abort on bad input.

    KindWhen
    TruncatedThe input ends inside a frame.
    CorruptThe input is not valid LZ4.
    ChecksumMismatchA header, block or content checksum fails, or the content size does not match.
    UnsupportedA version, block size or reserved bit the format does not define, or a legacy frame under until=EndOfMember.
    DictionaryRequiredThe frame names a dictionary and none was given.
    TrailingDataBytes after the last frame start no frame.
    LimitExceededMore than max_output.

    A block's bytes come out as they are decoded, before the checksums that cover them, so a streaming caller may hold bytes when a checksum fails. decompress returns only checked output. Errors stick: every later step raises the same kind until reset().

    #Not included

    High-compression levels (lz4hc, lz4 -3 to -12), compressing to fit a given output size, partial block decoding, dictionary training and multithreaded compression. Output from any of them decodes here.

    #License

    Apache-2.0. The compressor in src/encode.mbt follows lz4's LZ4_compress_generic, under the BSD 2-Clause license; see LICENSE-lz4.

    BlockSize

    pub(all) enum BlockSize {
    Max64KiB
    Max256KiB
    Max1MiB
    Max4MiB
    } derive(Eq,
    Debug
    )

    The largest uncompressed size of a frame's blocks, from its header.

    BlockSize::bytes

    fn BlockSize::bytes(self : BlockSize) -> Int

    The size in bytes.

    BlockSize::equal

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

    Compares two block sizes.

    BlockSize::not_equal

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

    Compares two block sizes.

    BlockSize::to_repr

    Shows the block size by its name, for tests and messages.

    Decoder

    pub struct Decoder {
    // private fields
    }

    A streaming LZ4 decoder: frames (with their checksums, dictionaries and content sizes), skippable frames and legacy frames, one after another. Feed it input in chunks of any size with step and collect output in slices of any size. It holds a 256 KiB window at most and a few header bytes, never a whole block, input or output.
    impl Decode for Decoder

    Decoder::Decoder

    fn Decoder::Decoder(until? :
    Until
    , dictionary? : BytesView) -> Decoder

    A decoder at the start of a stream.

    until says where the stream ends. EndOfInput, the default, decodes every frame up to the end of the input, skippable and legacy frames among them, as lz4 -d does. EndOfMember stops right after the first frame, a skippable frame included, and consumes nothing past it, so that input[last_consumed():] is what follows; a legacy frame, which ends only where the next frame or the input begins or ends, raises Unsupported under it.

    dictionary is the dictionary frames were written with (lz4 -D): its last 64 KiB come as if just before a frame's output, before every block of a frame of independent blocks. It serves every frame, whatever dictionary id the frame names (frame_info() says which); without it, a frame that names one raises DictionaryRequired(Some(id)). Legacy frames take no dictionary. The decoder keeps the dictionary by reference, and memory_usage does not count it.

    Decoder::frame_info

    fn Decoder::frame_info(self : Decoder) -> FrameInfo?

    What the header of the frame being decoded, or of the last one, says; None before the first frame's header. Skippable frames have none.

    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 consumed: all of it on NeedMoreInput; up to the error for a step that raised; for TrailingData, exactly up to the end of the stream.

    Decoder::last_produced

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

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

    Decoder::memory_usage

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

    Bytes the decoder holds: the window, at most 256 KiB (decoder_memory_bound()), allocated as output needs it. The header being read and the checksums' state (under 100 bytes) and the dictionary, the caller's, are not counted.

    Decoder::reset

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

    Back to the state of a new decoder with the same options; the window's memory is kept.

    Decoder::step

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

    Decodes from input into output. end says whether input holds the last bytes: the stream may end there, after a whole frame or inside a legacy frame's blocks, and anything cut short raises Truncated.

    Answers NeedMoreInput once all of input is taken and everything it decides is handed out, NeedMoreOutput while output waits for room, and Done at the end of the stream. A block's bytes come out as they are decoded, before the checksums that cover them are checked: they are provisional, as the byte-stream contract has it (decompress returns only checked output). A step that meets an error first hands out the output before it (answering NeedMoreOutput while it does not fit), then raises; after that the decoder raises it again, consuming and writing nothing, until reset.

    Encoder

    pub struct Encoder {
    // private fields
    }

    A streaming LZ4 frame encoder. It holds a block of input (64 KiB by default), the 64 KiB before it for linked blocks or a dictionary, the hash table and a block's output.
    impl Encode for Encoder

    Encoder::Encoder

    fn Encoder::Encoder(acceleration? : Int, block_size? : BlockSize, linked? : Bool, checksum? : Bool, block_checksum? : Bool, content_size? : Int64, dictionary? : BytesView, dictionary_id? : UInt) -> Encoder

    An encoder at the start of a frame.

    • acceleration: lz4's (lz4 --fast=N is N + 1): 1, the default, is lz4 -1; each step up searches less and compresses faster. Values below 1 count as 1, above 65,537 as 65,537.
    • block_size: the most input in a block, 64 KiB by default as lz4's library has it (lz4 the command uses 4 MiB, -B7).
    • linked: whether a block's matches may reach into the 64 KiB before it, which compresses small blocks better (true by default, as lz4's library has it; lz4 uses independent blocks, -BI). With independent blocks and no dictionary, each block is the bytes lz4 writes for it.
    • checksum: the frame ends with the XXH32 of its content (true by default, as lz4 writes it); block_checksum adds the XXH32 of each block's stored bytes.
    • content_size: written in the header, and the input must then be exactly that long: step raises ChecksumMismatch once it has more, or at Finish when it has less. A negative one counts as not given; 0 is held to but not written, as lz4's library has it (whose 0 means an unknown size).
    • dictionary: its last 64 KiB come before the frame's first block, or before every block when they are independent, as lz4 -D uses one; a decoder needs the same dictionary. dictionary_id is written in the header to name it, as lz4's library can (the command writes none). The encoder copies the dictionary's last 64 KiB.

    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 consumed.

    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 the encoder holds, the same from the first step to the last: the block and its history, the hash tables (4 bytes an entry), and a block's output with the header and footer, within encoder_memory_bound(block_size~).

    Encoder::reset

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

    Back to the state of a new encoder with the same options; the buffers' memory is kept.

    Encoder::step

    Compresses from input into output. Continue takes input, Flush writes what is held as a block, so that the output so far decodes to the input so far, and Finish does so and ends the frame. Input that was not taken (when the output is full) must be passed again, with the same action. Answers NeedMoreInput once everything is taken and handed out, 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) or at Finish when it falls short. The error sticks: later steps raise it again, taking and writing nothing, until reset.

    FrameInfo

    pub struct FrameInfo {
    block_size : BlockSize?
    linked : Bool
    block_checksum : Bool
    content_checksum : Bool
    content_size : UInt64?
    dictionary_id : UInt?
    legacy : Bool
    } derive(Eq,
    Debug
    )

    What a frame's header says. A legacy frame (lz4 -l) has blocks of 8 MiB and none of the other fields: its block_size is None.

    FrameInfo::equal

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

    Compares two frame headers, field by field.

    FrameInfo::not_equal

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

    Compares two frame headers, field by field.

    FrameInfo::to_repr

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

    block_compress_bound

    fn block_compress_bound(n : Int64) -> Int64

    The most bytes compress_block writes for n bytes of input: lz4's LZ4_COMPRESSBOUND, n + n / 255 + 16. A negative n counts as 0; past 2^62 the result is the largest Int64.

    compress

    fn compress(input : BytesView, acceleration? : Int, block_size? : BlockSize, linked? : Bool, checksum? : Bool, block_checksum? : Bool, dictionary? : BytesView, dictionary_id? : UInt) -> Bytes

    Compresses input into a whole frame, as Encoder with the same options writes it.

    compress_block

    fn compress_block(input : BytesView, acceleration? : Int, dictionary? : BytesView) -> Bytes

    Compresses input into one LZ4 block, with nothing around it: the caller keeps its length and the size it decodes to, which decompress_block needs a bound of. Without a dictionary these are the bytes lz4's LZ4_compress_fast writes, at the same acceleration (1, the default, compresses most; higher is faster; values below 1 count as 1). With dictionary, matches may reach into its last 64 KiB, as with LZ4_compress_fast_continue after LZ4_loadDict; the decoder needs the same dictionary. Inputs over 2,113,929,216 bytes, lz4's LZ4_MAX_INPUT_SIZE, abort.

    compress_bound

    fn compress_bound(n : Int64, block_size? : BlockSize) -> Int64

    The most bytes compress or an Encoder writes for n bytes of input in blocks of block_size: the header (19 bytes at most), each block's bytes with its size and checksum (a block is stored uncompressed rather than grow), the end mark and the content checksum. Each Flush adds a block's 8. A negative n counts as 0; past 2^62 the result is the largest Int64.

    decoder_memory_bound

    fn decoder_memory_bound() -> Int64

    The most Decoder::memory_usage reports: its window, 256 KiB.

    decompress

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

    Decodes a whole stream: frames, skippable frames and legacy frames one after another, as Decoder reads them. 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.

    decompress_block

    fn decompress_block(input : BytesView, max_output~ : Int, dictionary? : BytesView) -> Bytes raise
    CodecError

    Decodes one LZ4 block, all of input, as LZ4_decompress_safe does: max_output is what the caller knows of its decoded size (lz4's dstCapacity), and a block that decodes to more raises LimitExceeded({ resource: Output, .. }). With dictionary, matches may reach into its last 64 KiB (LZ4_decompress_safe_usingDict). A block must end with literals, as the format has it; one that does not raises Corrupt.

    encoder_memory_bound

    fn encoder_memory_bound(block_size? : BlockSize) -> Int64

    What Encoder::memory_usage reports at most for block_size, the same from the first step to the last: the block and 64 KiB of history, two hash tables of 2^13 entries, and a block's output with the header and footer.

    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 LZ4 frames.