snappy

    Snappy's raw and framing formats: a decoder and an encoder, streaming for the framing format, with CRC-32C checks.

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

    #gaato/snappy

    Snappy compression and decompression in pure MoonBit, for Native, JS, Wasm and Wasm GC. Use it to read and write Snappy's two formats: the raw format, which LevelDB and Parquet store, and the framing format of .sz files and snzip. Hadoop's and Kafka's Snappy streams use framings of their own, which this module does not read.

    The raw format is compressed and decompressed whole. The framing format is streamed: input in chunks of any size, output into buffers you choose, and each chunk's CRC-32C checked. The encoder follows Google's snappy and writes the same raw bytes. The framed decoder and encoder implement gaato/codec_bytes, so the same loop drives Zstandard, gzip and the other codecs of codecs.mbt.

    #Install

    moon add gaato/snappy

    #Compress and decompress bytes

    Pick the function by format: compress / decompress for the framing format, compress_raw / decompress_raw for the raw one.

    ///|
    test "compress and decompress" {
    let text = b"hello, hello, hello, snappy"
    // The framing format (.sz files, `snzip`).
    let framed = @snappy.compress(text)
    assert_eq(@snappy.decompress(framed, max_output=16 * 1024 * 1024), text)
    // The raw format (LevelDB, Parquet), with its length first.
    let raw = @snappy.compress_raw(text)
    assert_eq(@snappy.decompress_raw(raw, max_output=16 * 1024 * 1024), text)
    }

    ///|
    test "decode what snappy wrote" {
    let framed = b"\xff\x06\x00\x00sNaPpY\x01\x09\x00\x00\xbb\x1f\x1c\x19hello"
    assert_eq(@snappy.decompress(framed), b"hello")
    assert_eq(@snappy.decompress_raw(b"\x05\x10hello"), b"hello")
    }

    decompress and decompress_raw have no output cap unless you pass max_output. Set one for input that comes from elsewhere. decompress_raw checks the declared length against max_output before it allocates.

    #Decode a framed stream as it arrives

    Pass end=true once the source has run dry, with an empty input if need be, so that a stream cut short raises Truncated. An empty framed input is a valid empty stream.

    ///|
    /// 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 = @snappy.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 decoded = Buffer()
    decode_all(
    pieces_of([
    b"\xff\x06\x00\x00sNa", b"PpY\x01\x09\x00\x00\xbb\x1f", b"\x1c\x19hello",
    ]),
    bytes => decoded.write_bytes(bytes),
    )
    assert_eq(decoded.to_bytes(), b"hello")
    }

    The decoder reads streams one after another and skips padding and other skippable chunks. Decoder(until=EndOfMember) stops before the next stream's identifier. Encoder() streams the other way: Continue takes input, Flush writes what it holds as a chunk, and Finish ends the stream.

    The raw format has no streaming decoder: its length comes first and a copy may reach back to the start of the output, so a decoder must hold all of it anyway. For streams, use the framing format.

    #Defaults and limits

    OptionDefaultNotes
    verify_checksums (Decoder)truefalse skips the CRC-32C check.
    until (Decoder)EndOfInput
    max_output (decompress, decompress_raw)noneRaises LimitExceeded with resource: Output past it.

    The framed decoder holds at most 139 KiB (decoder_memory_bound()), and the encoder 245 KiB (encoder_memory_bound()). A compressed chunk longer than 76,494 bytes (the most 64 KiB can compress to) is valid in the format but no encoder writes one. The decoder refuses it with LimitExceeded, resource Memory.

    compress and compress_raw allocate their output at its bound first, so they abort for inputs near 2 GiB (an array's limit). An Encoder streams any length. compress_bound(n) and raw_compress_bound(n) give the bounds.

    #Errors

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

    KindWhen
    TruncatedThe input ends inside a chunk, or inside a raw stream's length.
    CorruptAnything else wrong in the stream.
    ChecksumMismatchA chunk's CRC-32C fails.
    LimitExceededA compressed chunk over 76,494 bytes (resource: Memory), or more than max_output (resource: Output).

    A chunk's bytes come out as soon as it is decoded, and ChecksumMismatch after them. decompress returns only checked output. Errors stick: every later step raises the same kind until reset().

    #Not included

    Snappy 1.2's higher compression level (its output decodes here like any stream), and hardware CRC instructions. For CRC-32C on its own, use gaato/crc.

    #License

    Apache-2.0.

    Decoder

    pub struct Decoder {
    // private fields
    }

    A streaming decoder of Snappy's framing format. It holds a chunk's body (at most 76,494 bytes) and its decoded bytes (at most 64 KiB), never the whole input or output.
    impl Decode for Decoder

    Decoder::Decoder

    fn Decoder::Decoder(until? :
    Until
    , verify_checksums? : Bool) -> Decoder

    A decoder at the start of a stream. until says where it ends: EndOfInput, the default, reads streams one after another up to the end of the input, as the format allows; EndOfMember stops before a stream identifier that follows data, the start of another stream, and consumes nothing of it. verify_checksums=false skips the CRC-32C of each chunk.

    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: a chunk's body and its decoded bytes, allocated at the first chunk that needs them, at most 76,494 and 65,536.

    Decoder::reset

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

    Back to the state of a new decoder with the same options; the buffers' 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. A chunk's bytes come out once it is decoded, and ChecksumMismatch after them when its CRC-32C fails: they are provisional, as the contract has it (decompress returns only checked output). end says whether input holds the last bytes: the stream ends there (nothing marks the end; no bytes at all are the empty stream), and a chunk cut short raises Truncated.

    Encoder

    pub struct Encoder {
    // private fields
    }

    A streaming encoder of Snappy's framing format: the stream identifier, then a chunk for each 64 KiB of input (the identifier alone for none, where the snap crate writes nothing), compressed unless that saves less than an eighth, as snappy's framing writers do. It holds 64 KiB of input and a chunk's output.
    impl Encode for Encoder

    Encoder::Encoder

    fn Encoder::Encoder() -> Encoder

    An encoder at the start of a stream.

    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 the encoder holds, the same from the first step to the last: 64 KiB of input, a chunk's output and the raw stream it is made from, and the hash table.

    Encoder::reset

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

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

    Encoder::step

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

    Compresses from input into output: Continue takes input, Flush writes what is held as a chunk, so that the output so far decodes to the input so far, and Finish does so and ends the stream. 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 stream has ended.

    compress

    fn compress(input : BytesView) -> Bytes

    Compresses input into a whole framed stream, as Encoder writes it. Inputs over 2,147,221,517 bytes abort: the output is allocated at its bound first, and theirs passes 2^31 - 1 bytes, the most an array holds; an Encoder streams them.

    compress_bound

    fn compress_bound(n : Int64) -> Int64

    The most bytes compress or an Encoder writes for n bytes of input: the 10-byte stream identifier, and for each chunk of up to 64 KiB its bytes and 8 more (a chunk is stored uncompressed rather than grow). Each Flush adds a chunk's 8. A negative n counts as 0; past 2^62 the result is the largest Int64.

    compress_raw

    fn compress_raw(input : BytesView) -> Bytes

    Compresses input into a whole raw Snappy stream, as snappy's Compress does: the length, then each 64 KiB fragment on its own. Inputs over 1,840,700,242 bytes abort: the output is allocated at its bound first, and theirs passes 2^31 - 1 bytes, the most an array holds.

    decoder_memory_bound

    fn decoder_memory_bound() -> Int64

    The most Decoder::memory_usage reports: the 4-byte chunk header, a chunk's body (76,494 bytes) and its decoded bytes (65,536).

    decompress

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

    Decodes a whole framed stream. 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_raw

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

    Decodes a whole raw Snappy stream. max_output caps the decoded length (2^31 - 1 by default, what an array holds): past it the stream raises LimitExceeded({ resource: Output, .. }) before anything is allocated. A length that the stream's bytes cannot make raises Corrupt, before anything is allocated too.

    encoder_memory_bound

    fn encoder_memory_bound() -> Int64

    What Encoder::memory_usage reports, the same from the first step to the last.

    raw_compress_bound

    fn raw_compress_bound(n : Int64) -> Int64

    The most bytes compress_raw writes for n bytes of input: snappy's MaxCompressedLength, 32 + n + n / 6. A negative n counts as 0.