Skip to content

Compute Huffman code lengths with Katajainen's algorithm only, as C does - #213

Open
kunpai wants to merge 1 commit into
google:masterfrom
kunpai:bit-lengths-length-limited
Open

kunpai wants to merge 1 commit into
google:masterfrom
kunpai:bit-lengths-length-limited

Conversation

@kunpai

@kunpai kunpai commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Compute Huffman code lengths with Katajainen's algorithm only, as C does

Problem

ZopfliCalculateBitLengths (C, Rust) gives each symbol its code length, at most maxbits (15 for the literal/length and distance codes, 7 for the code-length code). Every dynamic block's trees, and every block-size estimate, go through it. The two sides compute it differently:

# C Rust
1 algorithm Katajainen's length-limited algorithm, always a plain Huffman tree, and Katajainen's algorithm only when a length passes maxbits
2 allocation one leaf per symbol, used or not two nodes per symbol for the Huffman tree, and in Katajainen's algorithm a leaf per used symbol

1. Different code lengths, different output

When a Huffman tree's lengths fit in maxbits, both algorithms give optimal lengths for the symbols' counts. Often several sets of lengths are optimal, and the two algorithms can pick different ones. The trees then cost a different number of bits to write, and the block-size estimates that choose the block splits and block types can differ too. So the port's dynamic blocks differ from C's in bytes and sometimes in size. ZopfliGzipCompress with the default options, on files from the repository:

file C Rust
README 831 bytes 831 bytes, not the same bytes
COPYING 3,823 3,825
src/zopfli/deflate.c 7,890 7,892
src/zopfli/squeeze.c 5,270 5,271
src/zopfli/katajainen.c 2,751 2,748

Every stream decompresses to its file.

2. Different peak heap

For a literal/length code (288 symbols), C's leaves take 6,912 bytes and the port's Huffman nodes 18,432, whatever the counts. On a small block that is most of the heap: ZopfliCalculateBlockSize over an empty range with btype = 2 peaks at 6,912 bytes in C and 18,528 in the port.

Question

Which behaviour do we want: C's or the Rust port's? Specifically:

  1. should ZopfliCalculateBitLengths always use Katajainen's algorithm (like the C source), or a plain Huffman tree whenever its lengths fit in maxbits (like the Rust port)?
  2. should Katajainen's algorithm allocate a leaf for every symbol (like the C source), or only for the symbols that occur (like the Rust port)?

This PR implements C's behaviour.

Fix

-    unlimited_code_lengths(count, bitlengths)?;
-
-    let mut fallback = false;
-    for &len in bitlengths.iter() {
-        if len > maxbits as u32 {
-            fallback = true;
-            break;
-        }
-    }
-
-    if fallback {
-        crate::katajainen::length_limited_code_lengths(count, maxbits, bitlengths)?;
-    }
+    crate::katajainen::length_limited_code_lengths(count, maxbits, bitlengths)?;
-    let mut leaves = Vec::new();
+    let mut leaves = Vec::with_capacity(n);

The examples above then match C. Replayed before and after:

# C Rust main Rust patched
1 ZopfliGzipCompress, the five files above the sizes above different bytes on all five C's bytes on all five
1 ZopfliDeflate, btype = 3, README; both Rust columns with #212 813 bytes, bit pointer 7 813 bytes, not the same bytes, bit pointer 3 C's 813 bytes, bit pointer 7
2 ZopfliCalculateBlockSize, empty range, btype = 2, peak heap 6,912 18,528 4,608
2 the same, another campaign's record, peak heap 9,488 19,816 5,896

The peaks still differ, but within the harness's memory rule (it reports a divergence when the larger peak is at least 4 KiB and at least twice the smaller).

Notes for review:

  • One difference in Katajainen's algorithm is left, and this PR does not touch it. C sorts the leaves with LeafComparator, which returns a size_t difference as an int, so it mis-sorts once a count reaches about 4.2 million (2^31 >> 9). The port sorts correctly. ZopfliDeflate works in 1,000,000-byte master blocks, which keeps counts below that, so only a larger ZopfliDeflatePart range or ZopfliCalculateBlockSize store reaches it. Otherwise the two implementations gave the same lengths on 290,000 count sets (n = 19, 30, 32, 288; maxbits 7 and 15; many ties).
  • The port now runs Katajainen's algorithm on every call, as C does. unlimited_code_lengths is left in place: it is public, and nothing else in the crate calls it now.
  • The port's tests pass unchanged.

…C does

C's ZopfliCalculateBitLengths always calls ZopfliLengthLimitedCodeLengths,
which allocates one leaf per symbol. calculate_bit_lengths built an
unlimited Huffman tree first and ran Katajainen's algorithm only when a
length passed maxbits, so where several trees are optimal it could pick
a different one, and dynamic blocks differed from C's.

@1c3t3a 1c3t3a left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! We want C behavior!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants