hanki

deflate

stdlib/extra/deflate.hk: DEFLATE (RFC 1951), pure Hanki on both tiers.

The compressed stream every HTTP transfer coding, PNG IDAT chunk and gzip member is built on: a sequence of blocks, each holding either its bytes verbatim (stored), Huffman-coded symbols against the fixed table, or Huffman-coded symbols against tables the block states. inflate reads all three; deflate writes the first two, with no LZ77 match search. A native fast path can arrive behind these two functions without changing a caller.

The decoder is hostile-input-shaped. Caps states max_output_bytes and max_ratio, both checked as output is produced: a stream that expands without bound stops at the caller's budget. The working buffer has one i32 per output byte and doubles, and the finished value is copied once more, which puts peak memory at up to about nine times max_output_bytes. There is no uncapped form. A malformed stream is a typed InflateError carrying the offset or the limit, and never a partial value: the decoder either returns the whole output or no output.

The output buffer is an array.Array<i32> grown by copy_resize and read back for matches. A DEFLATE match copies bytes the stream produced earlier and a zero-copy writer cannot serve that read. BytesBuilder has no read side. The whole decode is therefore one @encapsulated function: no mutable value crosses a call boundary.

_at

def _at(src: bytes, i: int) -> int

Byte i of src, or 0 past the end. Every read is bounds-checked by the caller that needs the distinction.

_at32

def _at32(src: bytes, i: int) -> u32

Byte i of src as a fixed-width value, for the bit reader: a u32 shift and mask is one instruction on both tiers, where an int division builds and truncates a rational.

Caps

struct Caps
  max_output_bytes: int
  max_ratio: int
end

A decoder's budget. Both limits are mandatory: max_output_bytes is the absolute ceiling, and max_ratio bounds output bytes against input bytes, which is the form a decompression bomb takes.

Level

type Level
  Stored
  Fixed
end

The writer's two strategies. Stored is bytes verbatim, at five header bytes per 65,535-byte block. Fixed Huffman-codes each byte against the RFC 1951 fixed table with no match search: 8 bits per ASCII byte plus about two bytes of framing, which is smaller than Stored for ordinary text and about 0.44 bits per byte over the input for uniformly random bytes.

InflateError

type InflateError
  Truncated(int)
  TooLarge(int)
  Ratio(int)
  BadBlockType(int)
  BadLengths(int)
  BadHuffman(int)
  BadDistance(int)
  BadStoredLength(int)
  BadHeader(int)
  DictionaryRequired
  BadChecksum(int)
  UnsupportedMethod(int)
end

Why a compressed stream was refused, one variant per shape. The payload is an input offset (relative to the slice the decoder was handed) for Truncated, BadBlockType, BadHuffman at a failed code lookup, BadStoredLength and BadHeader; a cap for TooLarge and Ratio; the symbol count or symbol value the table check refused for BadLengths; the distance code or the distance for BadDistance; the method byte for UnsupportedMethod; and a checksum offset for BadChecksum.

FASTBITS

_FAST_BITS: int = 9

Bits of the input one lookup consumes. A code of this length or less is one table read; a longer one falls back to the canonical walk.

FASTSIZE

_FAST_SIZE: int = 512

2 ^ _FAST_BITS, the lookup table's size.

FASTMASK

_FAST_MASK: u32 = 511u32

The low _FAST_BITS bits of the reader, the lookup index.

Huffman

struct Huffman
  counts: Array<i32>
  symbols: Array<i32>
  fast: Array<i32>
end

A canonical Huffman table: how many codes each length has, and the symbols in code order, as _build_huffman lays them out. fast is the direct lookup: entry i is symbol << 4 | length for the code the next _FAST_BITS input bits spell when that code is short enough, and -1 where only the canonical walk can decide.

Inflated

struct Inflated
  output: bytes
  consumed: int
end

One decoded stream: the bytes and how many input bytes the stream used. A container decoder needs the count. Its trailer follows the stream and the next gzip member may follow the trailer.

LENGTHBASE

_LENGTH_BASE: List<int> = [
  3,
  4,
  5,
  6,
  7,
  8,
  9,
  10,
  11,
  13,
  15,
  17,
  19,
  23,
  27,
  31,
  35,
  43,
  51,
  59,
  67,
  83,
  99,
  115,
  131,
  163,
  195,
  227,
  258
]

Length codes 257..285: the base length and the extra bits it takes.

LENGTHEXTRA

_LENGTH_EXTRA: List<int> = [
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  1,
  1,
  1,
  1,
  2,
  2,
  2,
  2,
  3,
  3,
  3,
  3,
  4,
  4,
  4,
  4,
  5,
  5,
  5,
  5,
  0
]

DISTANCEBASE

_DISTANCE_BASE: List<int> = [
  1,
  2,
  3,
  4,
  5,
  7,
  9,
  13,
  17,
  25,
  33,
  49,
  65,
  97,
  129,
  193,
  257,
  385,
  513,
  769,
  1025,
  1537,
  2049,
  3073,
  4097,
  6145,
  8193,
  12289,
  16385,
  24577
]

Distance codes 0..29: the base distance and the extra bits it takes.

DISTANCEEXTRA

_DISTANCE_EXTRA: List<int> = [
  0,
  0,
  0,
  0,
  1,
  1,
  2,
  2,
  3,
  3,
  4,
  4,
  5,
  5,
  6,
  6,
  7,
  7,
  8,
  8,
  9,
  9,
  10,
  10,
  11,
  11,
  12,
  12,
  13,
  13
]

_reverse

def _reverse(code: int, length: int) -> int

A code of len bits reversed: a Huffman code is written most-significant bit first and the stream packs each byte least-significant bit first.

buildhuffman

def _build_huffman(lengths: List<int>, n: int) -> Result<Huffman, InflateError>

Build the canonical table for lengths, whose first n entries are symbol code lengths. An over-subscribed table is BadLengths, and an incomplete one is accepted only where it cannot hide a missing code: a table with at most one symbol, which is what a distance table of one code looks like.

fasttable

def _fast_table(counts: Array<i32>, symbols: Array<i32>) -> Array<i32>

The direct-lookup table for a canonical table: for each code of _FAST_BITS bits or fewer, every entry the code's low bits select is symbol << 4 | length. An entry left at -1 is one the canonical walk takes.

fixedlit

def _fixed_lit() -> Huffman

The RFC 1951 fixed literal/length table, built on demand: a fixed block is rare in modern output and a table per block costs less than a preload.

fixeddist

def _fixed_dist() -> Huffman

The RFC 1951 fixed distance table: 32 codes of five bits each.

_pow2

def _pow2(k: int) -> int

1 << k for a non-negative k, the extra-bits weight at bit position k.

CODEORDER

_CODE_ORDER: List<int> = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]

The order the code-length alphabet's lengths are stored in (RFC 1951 3.2.7).

inflate_stream

def inflate_stream(data: bytes, caps: Caps) -> Result<Inflated, InflateError>

Inflate the stream at the start of data, within caps, and report how many input bytes it used. Bytes after the final block are left to the caller, which is what a container decoder needs: its trailer follows the stream. A failure returns no bytes at all.

caps = Caps(max_output_bytes=1024, max_ratio=100)
compressed = compress("hello hello hello\n".to_bytes(), Stored)
inflate_stream(compressed, caps).map(|r| r.consumed).unwrap_or(0) => 23

inflate

def inflate(data: bytes, caps: Caps) -> Result<bytes, InflateError>

Inflate data and return the output alone. inflate_stream is the form a container decoder wants. The bytes after the stream are its trailer.

caps = Caps(max_output_bytes=1024, max_ratio=100)
compressed = compress("hello hello hello\n".to_bytes(), Stored)
inflate(compressed, caps).unwrap_or("".to_bytes()).to_string().unwrap_or("") => "hello hello hello\n"

FIXEDHELLO

_FIXED_HELLO: string = "cb48cdc9c957c84027b900"

RFC 1951 vectors produced by zlib 1.3: one per block shape, plus the container-free stored and empty streams.

FIXEDREPEAT

_FIXED_REPEAT: string = "4b4c4a4e494d4bcfc8cc4a1cd22c00"

EMPTYSTREAM

_EMPTY_STREAM: string = "0300"

ONEBYTE

_ONE_BYTE: string = "730400"

STOREDBLOCK

_STORED_BLOCK: string = "011400ebff73746f726564207061796c6f6164206279746573"

DYNAMICSTREAM

_DYNAMIC_STREAM: string = "05c10b4f82400000e0bf72dc110f79dcf1e84e08e44da80c53c12808b569ba965bb56a6bfdf9be4f0dac2443a0d5945fa7757331ebfdaa407731e67ab71ccac3753d3e0dbc30bab00c7bb61945fbe94bf75348dde5392c476da4a3c76fbea6225e3ec11496c6f0e9fd119470324d44d893b79dedf8791ca6678f952afef003402390663073a6e6bce2e0f4a23a31b18815637bc98515511a5566739e182deb24e3763b56ae2672f320eb4dde9802ae3593527a10c179f862af4765d116be6e2828d61bb89f1d77fb082c245cf8f4941a6ae7ae4c79b291d687e61e643dd4349fba2b000501bd77bc478899c7966c08416923c94a56769d32eb664e678e3a9921c68693b55b6b8eb029b6eba20aff01"

DYNAMICPLAIN

_DYNAMIC_PLAIN: string = "2c3f3343452320582d2b7939583a4627455c3d4e482350422f215c3a4c5e4c64355438675e24262a6d37452f3c343241416149665b7648285b6d62404c2a58412e235a75245436272f515d2244224c315e723c7b3023432129364327225c306c6034393d46424044683c374c2c2f713d3f20364120444522453949324b4e2122496d2c394230333033422f345121404e302b552c29374b24303158375b2831475f382b253e295559292e55465532262f542d32363636642720685e74376a652b4f58483d2e312b23422e5522614a65606141204f282f483d366744312c5b3a5232293e56285364555720455c222d2d3d363a522022262623705b243c3030324642332931263f4c34232833435234544437333b4b364a392c3e4a2337375e673360532d392656485f53484e40"

DEEPSTREAM

_DEEP_STREAM: string = "35540972eb3a0cbb0a482ddeddb869ba245d5e7f3bd3fbdfe80394d24c9d58124910006558e125c371de0d4880f9f1867438808cb5dac01f73baf1091e98e115d8f563e1ab559becc79e01ff020643c5e119edcfe08b323239bf8cff29a3a02c0f56f96a5b6631b82a5d3c2292b96a280617cb488e4bcb74de0af0643a66532e4a6abd0c8ab3325159c26ab79418b8daf61367c6000e1f549b7916acfec62cee4325aedfb9a5f00e389e4ce5572e99c5521156e09fde7422672cd98ae52f9d7eb4f3ef1407eb3dcd978e6f38192662db9d51cb2098ca8cecea7a72bebf464a173347d4c04d4f55ae0d8b9838089da94819dbcef69d0c655fd1f7d75a317b7566d95595cd23d55ce649c8778230f3ce133fb5fdbc656c33cf2dc760b123364b4248975d3c61cd41893e2c4950cb62d660668ca7b69b295fc2671025b0ffe552925bf96002f64c03487cc58cbba2eb067cdb41a86baa64e660ad12914a67679904b29642ec41b6714b5d1dc6fba6ae0fed0ea1069737f372f702134fccf025a6b4bdb9e80fafd026b8d6a667c5c7d9f26b7eacb44aaad5baf6b0135f75debb6f939e9f21f46c36bf89e0acc64997b46a73c2fabe3e02ef873d4707ad25557e8f3c7f2fc1ac8d68a6122763ecacea8b2dd2e843f18f8017f3421f1bfb486397685286a7487c6e32ce82b75efa241481a73b4f0becafcbe1685ea40716bcde20ba6d1147f95a9053936d60648c1ea7e1da3c8ee87bc1b6a9f98d7d6e0dd99fd0be16bb4f4b57a6ffca6a0ab60e9b95a2656f5b245b719c7d71ff7c58ce21bb7a5f7d8cc9b218a155b748b97b3f827f3acd41432573a90d29e6ace5075d45c2e389925c870d8d63ae1db97d8f5d4ea2f96c53badf1d9387b85260df029110c372c2b47bf286fe650e164bee37c5a38cd42f0c82873de112de96bea42af1fcef03ae54b0584c891ae33deaa84cf982218563de45d53fae3337757cf124df09bd8da96ca883b48ac68cba830b8d0fbf50b24c0d9db4d414035afb35c75a59b694e9ff07"

A dynamic block written by zlib 1.3 whose literal table has a ten-bit code, deeper than the fixed tables ever produce. The direct lookup covers nine bits. This stream is the one that reaches the canonical walk. The decoded bytes number _DEEP_BYTES and sum to _DEEP_SUM.

DEEPBYTES

_DEEP_BYTES: int = 1500

DEEPSUM

_DEEP_SUM: int = 53220

_unhex

def _unhex(text: string) -> Result<bytes, string>

The hex vector decoded: the test-side spelling of the fixtures above. The module decodes its own vectors so it needs no dependency on hex.

_raw

def _raw(text: string) -> bytes

A fixture decoded, with a failed decode left as an empty value so the assertion behind it fails in place of the helper diverging.

Code

struct Code
  bits: int
  length: int
end

One Huffman code: its bits and their count.

fixedcode

def _fixed_code(sym: int) -> Code

The fixed-table code and length for one symbol.

compress

def compress(data: bytes, level: Level) -> bytes

Compress data as a raw DEFLATE stream, with no container framing.

Stored writes the bytes verbatim in blocks of at most 65,535 bytes. The output never exceeds the input by more than five bytes per block. Fixed Huffman-codes each byte against the RFC 1951 fixed table with no match search; it exists to produce a Huffman-coded stream, and its output is larger than Stored for most inputs. Both are total: no input has a compressed form this module refuses to write.

caps = Caps(max_output_bytes=1024, max_ratio=100)
compressed = compress("hello hello hello\n".to_bytes(), Stored)
inflate(compressed, caps).unwrap_or("".to_bytes()).to_string().unwrap_or("") => "hello hello hello\n"