lzw

    LZW as GIF, TIFF, PDF and Unix compress (.Z) use it: a streaming decoder and encoder.

    lzw
    gif
    tiff
    compress
    codec
    Download zip
    Author
    Version
    0.1.1
    License
    Apache-2.0
    Last updated
    14 days ago
    Downloads
    44

    #gaato/lzw

    LZW compression and decompression in pure MoonBit, for Native, JS, Wasm and Wasm GC, in the four flavours files use: GIF's, TIFF's, PDF's and the .Z of Unix compress. Use it inside a GIF, TIFF or PDF reader or writer, or to read and write .Z files.

    Each flavour has a streaming decoder and encoder that take input in chunks of any size and write into output buffers you choose. They implement gaato/codec_bytes, so the same loop drives the other codecs of codecs.mbt. Output is checked against the reference compress (ncompress 5.0), gzip -d and other widely used LZW implementations.

    #Install

    moon add gaato/lzw

    #Choose the flavour from the container

    The flavours differ in bit order, when codes widen and how a stream ends, so pick the one your container uses:

    • GIF: Format::gif(min_code_size). Take the minimum code size from the byte before the image data, and join the data sub-blocks before decoding. The decoded bytes are palette indices.
    • TIFF: Format::tiff().
    • PDF (/LZWDecode): Format::pdf(), or Format::pdf(early_change=false) when the stream's parameters say /EarlyChange 0.
    • .Z files: Format::unix_compress(). The stream includes its header, which sets the width and block mode. stream_format() reports them.

    ///|
    test "compress and decompress" {
    let text = b"TOBEORNOTTOBEORTOBEORNOT"
    let gif = @lzw.Format::gif(8)
    let stream = @lzw.compress(text, gif)
    assert_eq(@lzw.decompress(stream, gif, max_output=16 * 1024 * 1024), text)
    let z = @lzw.Format::unix_compress()
    assert_eq(@lzw.decompress(@lzw.compress(text, z), z), text)
    }

    ///|
    test "decode what compress wrote" {
    // `printf 'hello hello hello' | compress -c -f`
    let z = b"\x1f\x9d\x90\x68\xca\xb0\x61\xf3\x06\x44\xc0\x81\x05\x0f\x12\x04"
    assert_eq(
    @lzw.decompress(z, @lzw.Format::unix_compress()),
    b"hello hello 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

    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(
    format : @lzw.Format,
    read : () -> Bytes?,
    write : (Bytes) -> Unit,
    ) -> Unit raise {
    let decoder = @lzw.Decoder(format)
    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 tiff = @lzw.Format::tiff()
    let stream = @lzw.compress(b"a strip of a TIFF image", tiff)
    let decoded = Buffer()
    let pieces = [stream[:5].to_owned(), stream[5:].to_owned()]
    decode_all(tiff, pieces_of(pieces), bytes => decoded.write_bytes(bytes))
    assert_eq(decoded.to_bytes(), b"a strip of a TIFF image")
    }

    • Missing end codes. Many writers leave GIF, TIFF and PDF streams without their end code. By default such a stream raises Truncated. Make the decoder with allow_missing_end=true to accept it.
    • Bytes after the end code. Decoder(format, until=EndOfMember) stops right after the end code and leaves what follows unread. .Z has no end code and raises Unsupported in that mode.
    • Encoding. Encoder(format) takes Continue and Finish. LZW cannot flush, so Flush raises Unsupported.

    #How the flavours differ

    FormatBits packed fromCodesWidensEnds
    gif(min_code_size)least significantclear 1 << n, end after it; n + 1 to 12 bitswhen the next code passes a power of twoat the end code
    tiff(), pdf()most significantclear 256, end 257; 9 to 12 bitsone code earlyat the end code
    pdf(early_change=false)most significantas TIFF'sas GIF'sat the end code
    unix_compress(max_bits~, block_mode~)least significantclear 256 in block mode, no end; 9 to max_bits (10 to 16)as GIF's, with padding at each width change and clearwith the input

    #Limits

    A decoder holds about 28 KiB for GIF, TIFF and PDF, and 448 KiB for 16-bit .Z (decoder_memory_bound(format)). An encoder holds 48 KiB and 768 KiB (encoder_memory_bound(format)). A .Z decoder refuses a stream wider than its format's max_bits with LimitExceeded, since the table grows with the width. compress_bound(n, format) is the most the encoder writes for n bytes.

    #Errors

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

    KindWhen
    TruncatedThe input ends before the end code, or inside .Z's header.
    CorruptA first code that is not a literal, a code past the table, or a .Z header that is not one.
    TrailingDataBytes after the end code.
    LimitExceededA .Z stream wider than max_bits (resource: Memory), or more than max_output (resource: Output).
    UnsupportedA .Z header over 16 bits or of 9 bits; .Z under EndOfMember; Flush; a GIF minimum code size outside 1 to 8 or a byte it cannot code; a .Z max_bits outside 10 to 16.

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

    #Not included

    9-bit .Z (compress 5.0 writes it, but the common readers decode it differently from how it was written, so no output is safe), the old least-significant-bit TIFF LZW, and other LZW variants such as ZIP's shrink. GIF sub-blocks and TIFF strips belong to those formats' readers.

    #License

    Apache-2.0.

    Decoder

    pub struct Decoder {
    // private fields
    }

    A streaming LZW decoder for one of the formats of Format.
    impl Decode for Decoder

    Decoder::Decoder

    fn Decoder::Decoder(format : Format, until? :
    Until
    , allow_missing_end? : Bool) -> Decoder

    A decoder at the start of a stream of format.

    until says where the stream ends: EndOfInput, the default, at the end of the input, and bytes after the end code are TrailingData; EndOfMember right after the end code, consuming nothing past its last byte. .Z has no end code: it ends with the input, and raises Unsupported under EndOfMember.

    allow_missing_end takes the end of the input as the end of a GIF, TIFF or PDF stream that lacks its end code, as many writers leave it out; without it, such a stream raises Truncated.

    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 table, 6 bytes a code, and a string of at most the table's length and a byte: 28 KiB for GIF, TIFF and PDF, 448 KiB for .Z of 16 bits (decoder_memory_bound(format)), allocated for .Z once its header gives its width.

    Decoder::reset

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

    Back to the state of a new decoder with the same options; the table'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. Answers NeedMoreInput once all of input is taken and its output handed out, NeedMoreOutput while output waits, and Done at the end of the stream. A step that meets an error first hands out the output before it, then raises; after that the decoder raises it again, consuming and writing nothing, until reset.

    Decoder::stream_format

    fn Decoder::stream_format(self : Decoder) -> Format

    The format the stream has: for .Z, with the header's max_bits and block_mode once it is read.

    Encoder

    pub struct Encoder {
    // private fields
    }

    A streaming LZW encoder for one of the formats of Format.
    impl Encode for Encoder

    Encoder::Encoder

    fn Encoder::Encoder(format : Format) -> Encoder

    An encoder of format. GIF, TIFF and PDF streams begin with a clear code and end with the end code; .Z begins with its header. With Format::gif(n) for n under 8, every input byte must be under 1 << n.

    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 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 hash table (twice the format's codes, 6 bytes a slot) and 256 bytes of output (encoder_memory_bound(format)).

    Encoder::reset

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

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

    Encoder::step

    Compresses from input into output. Continue takes input and Finish ends the stream; LZW has no way to flush, so Flush raises Unsupported. 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 and been handed out.

    Raises Unsupported for Flush, and for a byte a GIF minimum code size under 8 cannot code, once the output of the bytes before it is handed out (answering NeedMoreOutput while it does not fit); the error sticks until reset.

    Format

    pub struct Format {
    literal_bits : Int
    msb_first : Bool
    early_change : Bool
    max_bits : Int
    unix : Bool
    block_mode : Bool
    } derive(Eq,
    Debug
    )

    Which LZW a stream is: GIF's, TIFF's, PDF's or Unix compress's (.Z). Each fixes the bit order, the clear and end codes, the widths, and the point at which codes widen, as the format's references have it.

    Format::equal

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

    Compares two formats.

    Format::gif

    fn Format::gif(min_code_size : Int) -> Format raise
    CodecError

    GIF's LZW, as an image's data holds it once its sub-blocks are joined: codes packed from each byte's least significant bit, a clear code of 1 << min_code_size and an end code after it, codes from min_code_size + 1 to 12 bits. min_code_size is the byte before the image data, 2 to 8 (GIF allows no other; 1 is accepted, as some files have it); another raises Unsupported.

    Format::not_equal

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

    Compares two formats.

    Format::pdf

    fn Format::pdf(early_change? : Bool) -> Format

    PDF's LZWDecode filter: TIFF's LZW, with early_change the filter's EarlyChange (true, its default, is TIFF's; false widens codes one code later).

    Format::tiff

    fn Format::tiff() -> Format

    TIFF's LZW (compression 5): codes packed from each byte's most significant bit, clear 256 and end 257, 9 to 12 bits, widening one code early, as TIFF 6.0 and libtiff have it. The older TIFF LZW, packed from the least significant bit, is not this.

    Format::to_repr

    Shows a format by its fields.

    Format::unix_compress

    fn Format::unix_compress(max_bits? : Int, block_mode? : Bool) -> Format raise
    CodecError

    Unix compress's .Z: the header 1F 9D and a byte of flags, codes packed from each byte's least significant bit, from 9 bits up to max_bits (10 to 16; another raises Unsupported), widening as GIF's do, no end code, and in block_mode code 256 clearing the table. An encoder writes these into the header; a decoder takes them from the header, and refuses streams whose max_bits passes its own with LimitExceeded, since the table grows with it.

    compress

    fn compress(input : BytesView, format : Format) -> Bytes raise
    CodecError

    Compresses input into a whole stream of format, as Encoder writes it. Raises Unsupported for a byte a GIF minimum code size under 8 cannot code.

    compress_bound

    fn compress_bound(n : Int64, format : Format) -> Int64

    The most bytes compress or an Encoder writes for n bytes of input in format: every byte a code of the widest width, with the clear and end codes, a clear for every 3,000 bytes (no table is cleared sooner: a GIF or TIFF table after some 3,800 codes, a .Z one after 10,000 bytes) and, for .Z, the header and up to seven codes of padding at each of its eight widths after each clear. A negative n counts as 0; past 2^56 the result is the largest Int64.

    decoder_memory_bound

    fn decoder_memory_bound(format : Format) -> Int64

    The most Decoder::memory_usage reports for format: 7 bytes a code and one, 28,673 for GIF, TIFF and PDF, 458,753 for .Z of 16 bits.

    decompress

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

    Decodes a whole stream of format, as Decoder reads it. 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.

    encoder_memory_bound

    fn encoder_memory_bound(format : Format) -> Int64

    What Encoder::memory_usage reports for format, the same from the first step to the last: 12 bytes a code and 256, 49,408 for GIF, TIFF and PDF, 786,688 for .Z of 16 bits.