packkit/deflate

Pure Gleam DEFLATE (RFC 1951) encoder and decoder.

The decoder handles all three RFC 1951 block types (stored, fixed Huffman, dynamic Huffman) and enforces the Limits resource budget while decoding. The encoder exposes three entry points:

Values

pub fn codec() -> codec.Codec

Raw deflate codec smart constructor.

pub fn decode(
  bytes bytes: BitArray,
) -> Result(BitArray, error.CodecError)

Decode a raw DEFLATE byte stream using default limits.

pub fn decode_with_limits(
  bytes bytes: BitArray,
  limits limits: limit.Limits,
) -> Result(BitArray, error.CodecError)

Decode a raw DEFLATE byte stream using explicit limits.

pub fn decode_with_remainder(
  bytes bytes: BitArray,
  limits limits: limit.Limits,
) -> Result(#(BitArray, BitArray), error.CodecError)

Decode a DEFLATE stream AND return the byte slice that follows the last block in the input. Useful for wrappers like gzip that need to know exactly where the deflate stream ends so they can read a trailer immediately after it (and, for multi-member streams, the next member that comes after the trailer).

The remainder is byte-aligned: any partial bits left in the deflate decoder’s buffer after the last block are discarded as inter-block padding per RFC 1952 §2.2.

pub fn encode(
  bytes bytes: BitArray,
) -> Result(BitArray, error.CodecError)

Encode a byte stream as a fixed-Huffman DEFLATE block.

The encoder uses a greedy LZ77 match-finder with a 3-byte hash chain and a 32 KiB sliding window, then emits the resulting literal/length/distance tokens through the RFC 1951 fixed Huffman table.

pub fn encode_dynamic(
  bytes bytes: BitArray,
) -> Result(BitArray, error.CodecError)

Encode a byte stream as a dynamic-Huffman DEFLATE block (BTYPE=10).

Runs the same greedy LZ77 match-finder as [encode], but builds per-stream Huffman codes for the literal/length and distance alphabets from the observed symbol frequencies, then emits them as an RFC 1951 dynamic-Huffman block. This usually compresses better than the fixed-Huffman path on real-world inputs because rare symbols get longer codes and common symbols get shorter ones.

If the natural Huffman tree would exceed the RFC 1951 15-bit maximum code length for the literal/length or distance alphabet (which happens only on pathologically skewed inputs), the encoder transparently falls back to the fixed-Huffman path so the call still returns a valid stream.

pub fn encode_stored_only(
  bytes bytes: BitArray,
) -> Result(BitArray, error.CodecError)

Encode a byte stream as a sequence of stored (uncompressed) DEFLATE blocks. Useful when the caller wants to bypass the match-finder, for instance to test the framing in isolation.

Search Document