Skip to main content

lib_jsl_information/source_coders/
arithmetic.rs

1//! Manual arithmetic compression and decompression helpers.
2//!
3//! Arithmetic coding is another entropy coder, but unlike Huffman coding it
4//! does not assign one discrete bit-pattern per symbol. Instead, it keeps a
5//! numeric interval and progressively narrows that interval as each symbol is
6//! processed. Frequent symbols claim large sub-intervals and rare symbols claim
7//! small ones, which lets the coder represent symbol probabilities more
8//! precisely than a prefix tree.
9//!
10//! # Format Overview
11//!
12//! The compressed stream begins with the ASCII header `ARI0`. It is followed by
13//! everything the decoder needs to rebuild the exact same static probability
14//! model:
15//!
16//! - 4-byte magic header: `ARI0`
17//! - 8-byte little-endian original length
18//! - 2-byte little-endian symbol count
19//! - repeated `symbol_count` times:
20//!   - 1 byte: symbol value
21//!   - 4 bytes little-endian: symbol frequency (the symbol's count, or for inputs over 1 GiB,
22//!     the count rescaled so that the frequencies sum to at most 2^30)
23//! - 8-byte little-endian payload bit length
24//! - packed arithmetic-code bits in most-significant-bit-first order
25//!
26//! The implementation below uses a classic fixed-precision arithmetic coder
27//! with E1/E2/E3 renormalization. The comments in the hot paths explain how the
28//! interval is updated and why bits are emitted or consumed when the interval
29//! moves wholly into the low half, high half, or middle band.
30//!
31//! See the book entry [Entropy coding](https://jwkunz.github.io/lib_jsl/book/information/entropy-coding.html#arithmetic-coding).
32
33use lib_jsl_core::ErrorsJSL;
34
35const MAGIC: &[u8; 4] = b"ARI0";
36const CODE_VALUE_BITS: u32 = 32;
37const TOP_VALUE: u64 = (1u64 << CODE_VALUE_BITS) - 1;
38const FIRST_QTR: u64 = TOP_VALUE / 4 + 1;
39const HALF: u64 = 2 * FIRST_QTR;
40const THIRD_QTR: u64 = 3 * FIRST_QTR;
41/// The largest model total the coder handles exactly. After renormalisation the coding range is
42/// always more than a quarter of the full range, so with totals up to `FIRST_QTR` every symbol's
43/// sub-interval stays non-empty. Larger models (inputs over 1 GiB) are rescaled to fit.
44const MAX_TOTAL: u64 = FIRST_QTR;
45
46#[derive(Clone, Debug)]
47struct Model {
48    frequencies: [u32; 256],
49    cumulative: [u64; 257],
50    total: u64,
51}
52
53/// Compress a byte slice with a manual arithmetic coder.
54pub fn arithmetic_compress(input: &[u8]) -> Vec<u8> {
55    try_arithmetic_compress(input).unwrap_or_default()
56}
57
58/// Fallible variant of [`arithmetic_compress`].
59pub fn try_arithmetic_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
60    compress_with_limit(input, MAX_TOTAL)
61}
62
63/// Compresses with the model's total frequency limited to `limit` (at most [`MAX_TOTAL`]).
64fn compress_with_limit(input: &[u8], limit: u64) -> Result<Vec<u8>, ErrorsJSL> {
65    // We store the original length in the header, so the encoder first makes
66    // sure that length fits into the chosen 64-bit field.
67    if input.len() > u64::MAX as usize {
68        return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder input is too large to store its original length."));
69    }
70
71    // Build the static order-0 model once. Every later interval calculation is
72    // driven by these cumulative symbol counts.
73    let model = fit_model(build_model(input)?, limit)?;
74    let symbol_count = model.frequencies.iter().filter(|&&count| count > 0).count();
75
76    let mut output = Vec::new();
77    output.extend_from_slice(MAGIC);
78    output.extend_from_slice(&(input.len() as u64).to_le_bytes());
79    output.extend_from_slice(&(symbol_count as u16).to_le_bytes());
80
81    // Store the static model explicitly so decompression can reconstruct the
82    // same cumulative frequency table before it starts decoding bits.
83    for (symbol, &frequency) in model.frequencies.iter().enumerate() {
84        if frequency > 0 {
85            output.push(symbol as u8);
86            output.extend_from_slice(&frequency.to_le_bytes());
87        }
88    }
89
90    if input.is_empty() {
91        output.extend_from_slice(&0u64.to_le_bytes());
92        return Ok(output);
93    }
94
95    let mut writer = BitWriter::default();
96    let mut low = 0u64;
97    let mut high = TOP_VALUE;
98    let mut pending_bits = 0u64;
99
100    for &symbol in input {
101        // Convert the current symbol into its cumulative range `[cum_low,
102        // cum_high)` inside the model. Arithmetic coding does not jump to a
103        // codeword; it shrinks the active numeric interval to this slice.
104        let symbol_index = symbol as usize;
105        // ANCHOR: arithmetic_encode
106        let range = (high - low + 1) as u128;
107        let cum_low = model.cumulative[symbol_index] as u128;
108        let cum_high = model.cumulative[symbol_index + 1] as u128;
109        let total = model.total as u128;
110
111        // Narrow the current interval down to the slice owned by this symbol.
112        high = low + ((range * cum_high) / total - 1) as u64;
113        low += ((range * cum_low) / total) as u64;
114
115        // Renormalize whenever the interval has moved entirely into the low
116        // half, high half, or the middle "underflow" band.
117        loop {
118            if high < HALF {
119                // E1 scaling: the whole interval lies in the low half, so we
120                // can safely emit a leading `0` bit.
121                output_bit_plus_pending(&mut writer, false, &mut pending_bits);
122            } else if low >= HALF {
123                // E2 scaling: the whole interval lies in the high half, so we
124                // emit a leading `1` bit and subtract that half before
125                // rescaling back to the full range.
126                output_bit_plus_pending(&mut writer, true, &mut pending_bits);
127                low -= HALF;
128                high -= HALF;
129            } else if low >= FIRST_QTR && high < THIRD_QTR {
130                // E3 scaling: the interval sits in the ambiguous middle band.
131                // We cannot emit a stable leading bit yet, so we count one
132                // "pending" bit that will be resolved later.
133                pending_bits += 1;
134                low -= FIRST_QTR;
135                high -= FIRST_QTR;
136            } else {
137                break;
138            }
139
140            // After any renormalization step, stretch the interval back to the
141            // full fixed-precision range so the next symbol still has room to
142            // carve out a meaningful sub-interval.
143            low = low.saturating_mul(2);
144            high = high.saturating_mul(2).saturating_add(1);
145        }
146        // ANCHOR_END: arithmetic_encode
147    }
148
149    // Emit one final disambiguating bit plus any pending opposite bits so the
150    // decoder can safely land inside the final interval.
151    pending_bits += 1;
152    if low < FIRST_QTR {
153        output_bit_plus_pending(&mut writer, false, &mut pending_bits);
154    } else {
155        output_bit_plus_pending(&mut writer, true, &mut pending_bits);
156    }
157
158    let (payload_bytes, payload_bits) = writer.finish();
159    output.extend_from_slice(&payload_bits.to_le_bytes());
160    output.extend_from_slice(&payload_bytes);
161    Ok(output)
162}
163
164/// Decompress a byte slice previously produced by [`arithmetic_compress`].
165pub fn arithmetic_decompress(input: &[u8]) -> Vec<u8> {
166    try_arithmetic_decompress(input).unwrap_or_default()
167}
168
169/// Fallible variant of [`arithmetic_decompress`].
170pub fn try_arithmetic_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
171    // The header tells the decoder how many output bytes to expect and how to
172    // rebuild the same cumulative model used by the encoder.
173    if input.len() < MAGIC.len() || &input[..MAGIC.len()] != MAGIC {
174        return Err(ErrorsJSL::InvalidInputRange("Compressed payload is missing the arithmetic coder header."));
175    }
176
177    let mut cursor = MAGIC.len();
178    if cursor + 8 + 2 > input.len() {
179        return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder header is truncated before length or symbol count."));
180    }
181
182    let original_len = u64::from_le_bytes(
183        input[cursor..cursor + 8]
184            .try_into()
185            .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder original length field."))?,
186    ) as usize;
187    cursor += 8;
188
189    let symbol_count = u16::from_le_bytes(
190        input[cursor..cursor + 2]
191            .try_into()
192            .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder symbol count field."))?,
193    ) as usize;
194    cursor += 2;
195
196    let table_bytes = symbol_count
197        .checked_mul(5)
198        .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table size overflowed."))?;
199    if cursor + table_bytes + 8 > input.len() {
200        return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder header extends beyond the compressed payload."));
201    }
202
203    let mut frequencies = [0u32; 256];
204    for _ in 0..symbol_count {
205        let symbol = input[cursor];
206        let frequency = u32::from_le_bytes(
207            input[cursor + 1..cursor + 5]
208                .try_into()
209                .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder symbol frequency field."))?,
210        );
211        cursor += 5;
212
213        if frequency == 0 {
214            return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table cannot contain zero-frequency entries."));
215        }
216        if frequencies[symbol as usize] != 0 {
217            return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table contains duplicate symbol entries."));
218        }
219
220        frequencies[symbol as usize] = frequency;
221    }
222
223    let payload_bits = u64::from_le_bytes(
224        input[cursor..cursor + 8]
225            .try_into()
226            .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder payload bit length field."))?,
227    );
228    cursor += 8;
229
230    let payload = &input[cursor..];
231    let available_bits = (payload.len() as u64)
232        .checked_mul(8)
233        .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder payload size overflowed while checking bit capacity."))?;
234    if payload_bits > available_bits {
235        return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder payload bit length exceeds the available payload bytes."));
236    }
237
238    if original_len == 0 {
239        return Ok(Vec::new());
240    }
241
242    let model = build_model_from_frequencies(frequencies)?;
243    // The stored frequencies are the symbol counts, so they sum to the original length, unless
244    // the encoder rescaled them to fit the coder's precision.
245    let rescaled = model.total < original_len as u64 && model.total <= MAX_TOTAL;
246    if model.total as usize != original_len && !rescaled {
247        return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table does not match the stored original length."));
248    }
249
250    let mut reader = BitReader::new(payload, payload_bits);
251    let mut low = 0u64;
252    let mut high = TOP_VALUE;
253    let mut code = 0u64;
254
255    // Prime the decoder with an initial fixed-width code value assembled from
256    // the front of the packed payload. Missing tail bits are interpreted as
257    // zero, which matches how the encoder pads its final byte.
258    for _ in 0..CODE_VALUE_BITS {
259        code = (code << 1) | reader.read_bit_or_zero();
260    }
261
262    let mut output = Vec::with_capacity(original_len);
263
264    while output.len() < original_len {
265        let range = (high - low + 1) as u128;
266        let total = model.total as u128;
267
268        // Map the current code value back into the model's cumulative frequency
269        // space. This tells us which symbol sub-interval contains the code.
270        let scaled_value =
271            (((code - low + 1) as u128 * total - 1) / range) as u64;
272
273        let symbol = find_symbol(&model.cumulative, scaled_value)?;
274        output.push(symbol as u8);
275
276        // Now shrink the active interval to that symbol's slice, exactly the
277        // same way the encoder did when it originally saw this symbol.
278        let cum_low = model.cumulative[symbol] as u128;
279        let cum_high = model.cumulative[symbol + 1] as u128;
280
281        high = low + ((range * cum_high) / total - 1) as u64;
282        low += ((range * cum_low) / total) as u64;
283
284        loop {
285            if high < HALF {
286                // Nothing to subtract; the interval already sits in the low half.
287            } else if low >= HALF {
288                // Mirror the encoder's E2 normalization.
289                code -= HALF;
290                low -= HALF;
291                high -= HALF;
292            } else if low >= FIRST_QTR && high < THIRD_QTR {
293                // Mirror the encoder's E3 underflow handling.
294                code -= FIRST_QTR;
295                low -= FIRST_QTR;
296                high -= FIRST_QTR;
297            } else {
298                break;
299            }
300
301            // Pull one more payload bit into the live `code` register while the
302            // interval is stretched back to full precision.
303            low = low.saturating_mul(2);
304            high = high.saturating_mul(2).saturating_add(1);
305            code = code.saturating_mul(2).saturating_add(reader.read_bit_or_zero());
306        }
307    }
308
309    Ok(output)
310}
311
312fn build_model(input: &[u8]) -> Result<Model, ErrorsJSL> {
313    // The frequency table is the raw histogram of byte occurrences in the
314    // source. Arithmetic coding turns this histogram into cumulative counts.
315    let mut frequencies = [0u32; 256];
316    for &byte in input {
317        frequencies[byte as usize] = frequencies[byte as usize]
318            .checked_add(1)
319            .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency overflowed while counting symbols."))?;
320    }
321    build_model_from_frequencies(frequencies)
322}
323
324/// Rescales a model whose total exceeds `limit` so that it does not, keeping every symbol that
325/// occurs (each keeps a frequency of at least 1).
326fn fit_model(model: Model, limit: u64) -> Result<Model, ErrorsJSL> {
327    if model.total <= limit {
328        return Ok(model);
329    }
330    let present = model.frequencies.iter().filter(|&&f| f > 0).count() as u64;
331    if present > limit {
332        return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency limit is below the number of symbols."));
333    }
334    // Each symbol gets 1 plus its share of the remaining budget, so the total is at most `limit`.
335    let budget = (limit - present) as u128;
336    let mut scaled = [0u32; 256];
337    for (s, &f) in model.frequencies.iter().enumerate() {
338        if f > 0 {
339            scaled[s] = (1 + f as u128 * budget / model.total as u128) as u32;
340        }
341    }
342    build_model_from_frequencies(scaled)
343}
344
345fn build_model_from_frequencies(frequencies: [u32; 256]) -> Result<Model, ErrorsJSL> {
346    let mut cumulative = [0u64; 257];
347    for (index, &frequency) in frequencies.iter().enumerate() {
348        // `cumulative[i]` stores the total weight of all symbols strictly below
349        // `i`, so symbol `i` occupies `[cumulative[i], cumulative[i + 1))`.
350        cumulative[index + 1] = cumulative[index]
351            .checked_add(frequency as u64)
352            .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder cumulative frequency overflowed."))?;
353    }
354
355    Ok(Model {
356        frequencies,
357        cumulative,
358        total: cumulative[256],
359    })
360}
361
362fn find_symbol(cumulative: &[u64; 257], scaled_value: u64) -> Result<usize, ErrorsJSL> {
363    // Binary search is enough here because the cumulative table is monotonic.
364    // We are looking for the one symbol whose interval contains
365    // `scaled_value`.
366    let mut low = 0usize;
367    let mut high = 256usize;
368
369    while low < high {
370        let mid = (low + high) / 2;
371        if cumulative[mid + 1] <= scaled_value {
372            low = mid + 1;
373        } else if cumulative[mid] > scaled_value {
374            high = mid;
375        } else {
376            return Ok(mid);
377        }
378    }
379
380    Err(ErrorsJSL::InvalidInputRange("Arithmetic coder could not map the current code value to a symbol interval."))
381}
382
383fn output_bit_plus_pending(writer: &mut BitWriter, bit: bool, pending_bits: &mut u64) {
384    // Emit the stable leading bit we just discovered.
385    writer.write_bit(bit);
386    while *pending_bits > 0 {
387        // Every postponed middle-band event resolves to the opposite bit once
388        // the final direction becomes known.
389        writer.write_bit(!bit);
390        *pending_bits -= 1;
391    }
392}
393
394#[derive(Default)]
395struct BitWriter {
396    bytes: Vec<u8>,
397    current_byte: u8,
398    bits_in_current_byte: u8,
399    bits_written: u64,
400}
401
402impl BitWriter {
403    fn write_bit(&mut self, bit: bool) {
404        self.current_byte <<= 1;
405        if bit {
406            self.current_byte |= 1;
407        }
408        self.bits_in_current_byte += 1;
409        self.bits_written += 1;
410
411        if self.bits_in_current_byte == 8 {
412            self.bytes.push(self.current_byte);
413            self.current_byte = 0;
414            self.bits_in_current_byte = 0;
415        }
416    }
417
418    fn finish(mut self) -> (Vec<u8>, u64) {
419        if self.bits_in_current_byte > 0 {
420            self.current_byte <<= 8 - self.bits_in_current_byte;
421            self.bytes.push(self.current_byte);
422        }
423        (self.bytes, self.bits_written)
424    }
425}
426
427struct BitReader<'a> {
428    bytes: &'a [u8],
429    total_bits: u64,
430    bit_position: u64,
431}
432
433impl<'a> BitReader<'a> {
434    fn new(bytes: &'a [u8], total_bits: u64) -> Self {
435        Self {
436            bytes,
437            total_bits,
438            bit_position: 0,
439        }
440    }
441
442    fn read_bit_or_zero(&mut self) -> u64 {
443        if self.bit_position >= self.total_bits {
444            return 0;
445        }
446
447        let byte_index = (self.bit_position / 8) as usize;
448        let bit_index = 7 - (self.bit_position % 8) as u8;
449        self.bit_position += 1;
450        ((self.bytes[byte_index] >> bit_index) & 1) as u64
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    #[test]
459    fn round_trip_empty_input() {
460        let payload = b"";
461        let compressed = try_arithmetic_compress(payload).unwrap();
462        let decompressed = try_arithmetic_decompress(&compressed).unwrap();
463
464        assert_eq!(decompressed, payload);
465        assert_eq!(&compressed[..MAGIC.len()], MAGIC);
466    }
467
468    #[test]
469    fn round_trip_repeated_text() {
470        let payload = b"BANANA_BANDANA_BANANA_BANDANA";
471        let compressed = try_arithmetic_compress(payload).unwrap();
472        let decompressed = try_arithmetic_decompress(&compressed).unwrap();
473
474        assert_eq!(decompressed, payload);
475    }
476
477    #[test]
478    fn round_trip_binary_data() {
479        let payload = [0u8, 1, 1, 2, 3, 5, 8, 13, 13, 13, 21, 34, 55];
480        let compressed = try_arithmetic_compress(&payload).unwrap();
481        let decompressed = try_arithmetic_decompress(&compressed).unwrap();
482
483        assert_eq!(decompressed, payload);
484    }
485
486    #[test]
487    fn round_trip_single_symbol_input() {
488        let payload = [9u8; 2048];
489        let compressed = try_arithmetic_compress(&payload).unwrap();
490        let decompressed = try_arithmetic_decompress(&compressed).unwrap();
491
492        assert_eq!(decompressed, payload);
493    }
494
495    #[test]
496    fn round_trip_kjv_text_asset() {
497        let payload = include_bytes!("../../test_assets/kjv.txt");
498        let compressed = try_arithmetic_compress(payload).unwrap();
499        let decompressed = try_arithmetic_decompress(&compressed).unwrap();
500
501        assert_eq!(decompressed, payload);
502    }
503
504    #[test]
505    fn a_model_too_large_for_the_coder_is_rescaled() {
506        // Inputs over 1 GiB exceed the coder's precision; test the same path with a small limit.
507        let payload = include_bytes!("../../test_assets/kjv.txt");
508        let compressed = compress_with_limit(payload, 1000).unwrap();
509        let symbol_count = u16::from_le_bytes([compressed[12], compressed[13]]) as usize;
510        let total: u64 = (0..symbol_count).map(|k| u32::from_le_bytes(compressed[15 + 5 * k..19 + 5 * k].try_into().unwrap()) as u64).sum();
511        assert!(total <= 1000, "stored total {total}");
512        assert_eq!(try_arithmetic_decompress(&compressed).unwrap(), payload);
513        // The coarser model costs a little compression.
514        assert!(compressed.len() > try_arithmetic_compress(payload).unwrap().len());
515    }
516
517    #[test]
518    fn malformed_stream_returns_error() {
519        let malformed = vec![b'A', b'R', b'I', b'0', 0x01];
520        let result = try_arithmetic_decompress(&malformed);
521
522        assert!(result.is_err());
523    }
524
525    #[test]
526    fn wrapper_returns_empty_on_malformed_stream() {
527        let malformed = vec![0x01, 0x02, 0x03];
528        let decompressed = arithmetic_decompress(&malformed);
529
530        assert!(decompressed.is_empty());
531    }
532}