infotheory 1.1.1

The algorithmic information theory library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! rANS (range Asymmetric Numeral System) coder with an optional multi-lane path.
//!
//! The primary implementation is scalar and portable. On x86_64 builds, this
//! module also exposes an 8-lane interleaved encoder/decoder API.
//!
//! # Design
//!
//! - Uses 8-way parallel rANS states for throughput
//! - 15-bit precision for probability quantization
//! - Interleaved bitstream for decoder efficiency
//! - Supports both streaming and batch modes

/// Number of bits for rANS probability precision
pub const ANS_BITS: u32 = 15;

/// Total probability range (2^15 = 32768)
pub const ANS_TOTAL: u32 = 1 << ANS_BITS;

/// Lower bound for rANS state (2^15)
pub const ANS_LOW: u32 = 1 << ANS_BITS;

/// Upper bound for rANS state (2^31)
pub const ANS_HIGH: u32 = 1 << 31;

/// rANS CDF representation for a symbol.
#[derive(Clone, Debug)]
pub struct Cdf {
    /// Lower cumulative probability bound
    pub lo: u32,
    /// Upper cumulative probability bound  
    pub hi: u32,
    /// Total probability (should be ANS_TOTAL)
    pub total: u32,
}

impl Cdf {
    /// Create a new CDF entry.
    #[inline]
    pub fn new(lo: u32, hi: u32, total: u32) -> Self {
        Self { lo, hi, total }
    }

    /// Get the frequency (hi - lo).
    #[inline]
    pub fn freq(&self) -> u32 {
        self.hi - self.lo
    }
}

/// Quantize PDF to rANS CDF table with guaranteed minimum frequencies.
///
/// This implements a robust quantization algorithm that ensures:
/// 1. All symbols with p > 0 get freq >= 1
/// 2. The total equals ANS_TOTAL exactly
/// 3. Monotonicity is preserved (`cdf[i+1] >= cdf[i]`)
///
/// Uses error diffusion to distribute rounding errors across symbols.
///
/// # Arguments
/// * `pdf` - Probability distribution (must sum to ~1.0)
///
/// # Returns
/// CDF table where `cdf[i]` = cumulative probability up to symbol i
pub fn quantize_pdf_to_rans_cdf(pdf: &[f64]) -> Vec<u32> {
    let mut cdf = vec![0u32; pdf.len() + 1];
    let mut freqs = vec![0i64; pdf.len()];
    quantize_pdf_to_rans_cdf_with_buffer(pdf, &mut cdf, &mut freqs);
    cdf
}

/// Quantize PDF to rANS CDF using reusable scratch buffers.
///
/// * `cdf_out` must have length at least `pdf.len() + 1`
/// * `freq_buf` must have length at least `pdf.len()`
/// * `index_buf` must have length at least `pdf.len()`
pub fn quantize_pdf_to_rans_cdf_with_buffer(
    pdf: &[f64],
    cdf_out: &mut [u32],
    freq_buf: &mut [i64],
) {
    let n = pdf.len();
    super::quantize_pdf_to_integer_cdf_with_buffer(pdf, ANS_TOTAL, cdf_out, freq_buf);

    debug_assert_eq!(cdf_out[n], ANS_TOTAL, "CDF total must equal ANS_TOTAL");
    for i in 0..n {
        if pdf[i] > 0.0 {
            debug_assert!(
                cdf_out[i + 1] > cdf_out[i],
                "Symbol {} with p={} has zero frequency",
                i,
                pdf[i]
            );
        }
    }
}

/// Get Cdf for a symbol from a CDF table.
#[inline]
pub fn cdf_for_symbol(cdf: &[u32], sym: usize) -> Cdf {
    Cdf::new(cdf[sym], cdf[sym + 1], ANS_TOTAL)
}

/// Scalar rANS encoder.
pub struct RansEncoder {
    state: u32,
    output: Vec<u16>, // 16-bit words for output
}

impl RansEncoder {
    /// Create a new rANS encoder.
    pub fn new() -> Self {
        Self {
            state: ANS_LOW,
            output: Vec::new(),
        }
    }

    /// Encode a symbol using its CDF bounds.
    ///
    /// rANS encoding formula:
    /// x' = (x / freq) << ANS_BITS + (x % freq) + c_lo
    #[inline]
    pub fn encode(&mut self, cdf: &Cdf) {
        let freq = cdf.freq();
        debug_assert!(freq > 0, "Symbol frequency must be > 0");

        // Renormalize: output 16-bit words while state >= max allowed
        // Max state after encode: freq * (2^16) - 1, we need this < ANS_HIGH
        // So we renorm when state >= (freq << (32 - 1 - ANS_BITS)) = freq << 16
        while self.state >= (freq << 16) {
            self.output.push(self.state as u16);
            self.state >>= 16;
        }

        // Encode: x' = (x / freq) << ANS_BITS + (x % freq) + c_lo
        let q = self.state / freq;
        let r = self.state % freq;
        self.state = (q << ANS_BITS) + r + cdf.lo;
    }

    /// Encode a symbol given a PDF.
    pub fn encode_pdf(&mut self, pdf: &[f64], sym: usize) {
        let cdf_table = quantize_pdf_to_rans_cdf(pdf);
        let cdf = cdf_for_symbol(&cdf_table, sym);
        self.encode(&cdf);
    }

    /// Finish encoding and return the output bytes.
    pub fn finish(self) -> Vec<u8> {
        // Output final state (4 bytes)
        let mut result = Vec::with_capacity(self.output.len() * 2 + 4);

        // Push final state first (will be read first during decode)
        result.extend_from_slice(&self.state.to_le_bytes());

        // Push output words in reverse order (LIFO)
        for &word in self.output.iter().rev() {
            result.extend_from_slice(&word.to_le_bytes());
        }

        result
    }

    /// Get current output size estimate.
    pub fn size_estimate(&self) -> usize {
        self.output.len() * 2 + 4 // *2 for u16->bytes, +4 for final state
    }
}

impl Default for RansEncoder {
    fn default() -> Self {
        Self::new()
    }
}

/// Scalar rANS decoder.
pub struct RansDecoder<'a> {
    state: u32,
    input: &'a [u8],
    pos: usize,
}

impl<'a> RansDecoder<'a> {
    /// Create a new rANS decoder from input bytes.
    pub fn new(input: &'a [u8]) -> anyhow::Result<Self> {
        if input.len() < 4 {
            anyhow::bail!("rANS input too short");
        }

        // Read initial state (little-endian, first 4 bytes)
        let state = u32::from_le_bytes([input[0], input[1], input[2], input[3]]);

        Ok(Self {
            state,
            input,
            pos: 4,
        })
    }

    /// Decode a symbol using a CDF table.
    ///
    /// rANS decoding:
    /// 1. Extract slot = state % total (= state & (ANS_TOTAL - 1))
    /// 2. Find symbol `s` where `cdf[s] <= slot < cdf[s+1]`
    /// 3. Update state: x' = freq * (x >> ANS_BITS) + (x & (ANS_TOTAL-1)) - c_lo
    #[inline]
    pub fn decode(&mut self, cdf: &[u32]) -> anyhow::Result<usize> {
        // Extract slot from state (low ANS_BITS bits)
        let slot = self.state & (ANS_TOTAL - 1);

        // Binary search for symbol `s` where `cdf[s] <= slot < cdf[s+1]`
        let mut lo = 0usize;
        let mut hi = cdf.len() - 1;
        while lo + 1 < hi {
            let mid = (lo + hi) / 2;
            if cdf[mid] <= slot {
                lo = mid;
            } else {
                hi = mid;
            }
        }
        let sym = lo;

        let c_lo = cdf[sym];
        let c_hi = cdf[sym + 1];
        let freq = c_hi - c_lo;

        // Decode: x' = freq * (x >> ANS_BITS) + (x & (ANS_TOTAL-1)) - c_lo
        self.state = freq * (self.state >> ANS_BITS) + slot - c_lo;

        // Renormalize: read 16-bit words while state < ANS_LOW
        while self.state < ANS_LOW && self.pos + 1 < self.input.len() {
            let word = u16::from_le_bytes([self.input[self.pos], self.input[self.pos + 1]]);
            self.state = (self.state << 16) | (word as u32);
            self.pos += 2;
        }

        Ok(sym)
    }

    /// Decode a symbol given a PDF.
    pub fn decode_pdf(&mut self, pdf: &[f64]) -> anyhow::Result<usize> {
        let cdf = quantize_pdf_to_rans_cdf(pdf);
        self.decode(&cdf)
    }
}

// =============================================================================
// 8-way interleaved rANS API (x86_64 build target)
// =============================================================================

#[cfg(target_arch = "x86_64")]
mod simd {
    use super::*;

    /// Number of parallel rANS streams
    pub const RANS_LANES: usize = 8;

    /// 8-way interleaved rANS encoder.
    pub struct SimdRansEncoder {
        states: [u32; RANS_LANES],
        outputs: [Vec<u8>; RANS_LANES],
        lane: usize,
    }

    impl SimdRansEncoder {
        /// Create a new SIMD rANS encoder.
        pub fn new() -> Self {
            Self {
                states: [ANS_LOW; RANS_LANES],
                outputs: Default::default(),
                lane: 0,
            }
        }

        /// Encode a symbol, cycling through lanes.
        pub fn encode(&mut self, cdf: &Cdf) {
            let freq = cdf.freq();
            let lane = self.lane;
            self.lane = (self.lane + 1) % RANS_LANES;

            let state = &mut self.states[lane];
            let output = &mut self.outputs[lane];

            // Renormalize
            while *state >= (ANS_HIGH / cdf.total) * freq {
                output.push(*state as u8);
                *state >>= 8;
            }

            // Encode
            *state = ((*state / freq) * cdf.total) + (*state % freq) + cdf.lo;
        }

        /// Finish encoding and return interleaved output.
        pub fn finish(self) -> Vec<u8> {
            let mut result = Vec::new();

            // Output final states (interleaved)
            for &s in self.states.iter().take(RANS_LANES) {
                result.extend_from_slice(&s.to_le_bytes());
            }

            // Find max output length
            let max_len = self.outputs.iter().map(|v| v.len()).max().unwrap_or(0);

            // Interleave output bytes
            for pos in 0..max_len {
                for lane in 0..RANS_LANES {
                    let out = &self.outputs[lane];
                    if pos < out.len() {
                        result.push(out[out.len() - 1 - pos]);
                    } else {
                        result.push(0);
                    }
                }
            }

            result
        }
    }

    impl Default for SimdRansEncoder {
        fn default() -> Self {
            Self::new()
        }
    }

    /// 8-way interleaved rANS decoder.
    pub struct SimdRansDecoder<'a> {
        states: [u32; RANS_LANES],
        input: &'a [u8],
        pos: usize,
        lane: usize,
    }

    impl<'a> SimdRansDecoder<'a> {
        /// Create a new SIMD rANS decoder.
        pub fn new(input: &'a [u8]) -> anyhow::Result<Self> {
            if input.len() < RANS_LANES * 4 {
                anyhow::bail!("SIMD rANS input too short");
            }

            let mut states = [0u32; RANS_LANES];
            for (i, state) in states.iter_mut().enumerate() {
                let offset = i * 4;
                *state = u32::from_le_bytes([
                    input[offset],
                    input[offset + 1],
                    input[offset + 2],
                    input[offset + 3],
                ]);
            }

            Ok(Self {
                states,
                input,
                pos: RANS_LANES * 4,
                lane: 0,
            })
        }

        /// Decode a symbol from the current lane.
        pub fn decode(&mut self, cdf: &[u32]) -> anyhow::Result<usize> {
            let lane = self.lane;
            self.lane = (self.lane + 1) % RANS_LANES;

            let state = &mut self.states[lane];
            let total = ANS_TOTAL;
            let value = *state & (total - 1);

            // Binary search
            let mut lo = 0usize;
            let mut hi = cdf.len() - 1;
            while lo + 1 < hi {
                let mid = (lo + hi) / 2;
                if cdf[mid] <= value {
                    lo = mid;
                } else {
                    hi = mid;
                }
            }
            let sym = lo;

            let c_lo = cdf[sym];
            let c_hi = cdf[sym + 1];
            let freq = c_hi - c_lo;

            // Decode
            *state = freq * (*state >> ANS_BITS) + (*state & (total - 1)) - c_lo;

            // Renormalize (read from interleaved stream)
            while *state < ANS_LOW {
                // Read byte for this lane
                let byte_idx = self.pos + lane;
                if byte_idx < self.input.len() {
                    *state = (*state << 8) | (self.input[byte_idx] as u32);
                }
                self.pos += RANS_LANES;
            }

            Ok(sym)
        }
    }
}
#[cfg(target_arch = "x86_64")]
/// SIMD lane-parallel rANS types on x86_64.
pub use simd::*;

#[cfg(not(target_arch = "x86_64"))]
/// Number of SIMD lanes for the portable fallback (single-lane).
pub const RANS_LANES: usize = 1;

#[cfg(not(target_arch = "x86_64"))]
/// Portable wrapper that maps SIMD encoder API to scalar rANS.
pub struct SimdRansEncoder {
    inner: RansEncoder,
}

#[cfg(not(target_arch = "x86_64"))]
impl SimdRansEncoder {
    /// Create a fallback single-lane encoder.
    pub fn new() -> Self {
        Self {
            inner: RansEncoder::new(),
        }
    }

    /// Encode one symbol using scalar rANS.
    pub fn encode(&mut self, cdf: &Cdf) {
        self.inner.encode(cdf);
    }

    /// Finalize encoding and return encoded bytes.
    pub fn finish(self) -> Vec<u8> {
        self.inner.finish()
    }
}

#[cfg(not(target_arch = "x86_64"))]
impl Default for SimdRansEncoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_arch = "x86_64"))]
/// Portable wrapper that maps SIMD decoder API to scalar rANS.
pub struct SimdRansDecoder<'a> {
    inner: RansDecoder<'a>,
}

#[cfg(not(target_arch = "x86_64"))]
impl<'a> SimdRansDecoder<'a> {
    /// Create a fallback single-lane decoder.
    pub fn new(input: &'a [u8]) -> anyhow::Result<Self> {
        Ok(Self {
            inner: RansDecoder::new(input)?,
        })
    }

    /// Decode one symbol using scalar rANS.
    pub fn decode(&mut self, cdf: &[u32]) -> anyhow::Result<usize> {
        self.inner.decode(cdf)
    }
}

// =============================================================================
// Blocked rANS for streaming large files
// =============================================================================

/// Block size for blocked rANS (128KB)
pub const BLOCK_SIZE: usize = 128 * 1024;

/// Blocked rANS encoder for streaming large files.
///
/// Splits input into 128KB blocks and encodes each independently.
/// This allows O(1) memory for encoding arbitrary-sized inputs.
pub struct BlockedRansEncoder {
    /// Symbols buffered for current block (stores low/high bounds only)
    symbols: Vec<Cdf>,
    /// Encoded blocks
    blocks: Vec<Vec<u8>>,
}

impl BlockedRansEncoder {
    /// Create an empty blocked encoder.
    pub fn new() -> Self {
        Self {
            symbols: Vec::with_capacity(BLOCK_SIZE),
            blocks: Vec::new(),
        }
    }

    /// Encode a symbol with its CDF.
    pub fn encode(&mut self, cdf: Cdf) {
        self.symbols.push(cdf);

        // Flush block if full
        if self.symbols.len() >= BLOCK_SIZE {
            self.flush_block();
        }
    }

    /// Flush the current block.
    fn flush_block(&mut self) {
        if self.symbols.is_empty() {
            return;
        }

        // Encode in reverse order (rANS is LIFO)
        let mut encoder = RansEncoder::new();
        for cdf in self.symbols.iter().rev() {
            encoder.encode(cdf);
        }

        let encoded = encoder.finish();
        self.blocks.push(encoded);
        self.symbols.clear();
    }

    /// Finish encoding and return all blocks.
    pub fn finish(mut self) -> Vec<Vec<u8>> {
        // Flush any remaining symbols
        self.flush_block();
        self.blocks
    }
}

impl Default for BlockedRansEncoder {
    fn default() -> Self {
        Self::new()
    }
}

/// Blocked rANS decoder for streaming large files.
pub struct BlockedRansDecoder<'a> {
    blocks: Vec<&'a [u8]>,
    current_block: usize,
    symbols_remaining_in_block: usize,
    total_symbols: usize,
    decoder: Option<RansDecoder<'a>>,
}

impl<'a> BlockedRansDecoder<'a> {
    /// Create a new blocked decoder from encoded blocks.
    pub fn new(blocks: Vec<&'a [u8]>, total_symbols: usize) -> anyhow::Result<Self> {
        let expected_blocks = if total_symbols == 0 {
            0
        } else {
            total_symbols.div_ceil(BLOCK_SIZE)
        };
        if blocks.len() != expected_blocks {
            anyhow::bail!(
                "blocked rANS expected {expected_blocks} blocks for {total_symbols} symbols, got {}",
                blocks.len()
            );
        }
        Ok(Self {
            blocks,
            current_block: 0,
            symbols_remaining_in_block: 0,
            total_symbols,
            decoder: None,
        })
    }

    #[inline]
    fn open_block(&mut self, block_index: usize) -> anyhow::Result<()> {
        if block_index >= self.blocks.len() {
            anyhow::bail!("No more blocks to decode");
        }
        let consumed = block_index.saturating_mul(BLOCK_SIZE);
        let remaining = self.total_symbols.saturating_sub(consumed);
        self.current_block = block_index;
        self.symbols_remaining_in_block = remaining.min(BLOCK_SIZE);
        self.decoder = Some(RansDecoder::new(self.blocks[block_index])?);
        Ok(())
    }

    /// Decode next symbol with provided CDF.
    pub fn decode(&mut self, cdf: &[u32]) -> anyhow::Result<usize> {
        if self.symbols_remaining_in_block == 0 {
            if self.decoder.is_some() {
                self.open_block(self.current_block + 1)?;
            } else {
                self.open_block(0)?;
            }
        }

        let sym = self
            .decoder
            .as_mut()
            .expect("decoder initialized for current block")
            .decode(cdf)?;
        self.symbols_remaining_in_block = self.symbols_remaining_in_block.saturating_sub(1);
        Ok(sym)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_roundtrip_scalar() {
        let pdf = vec![0.5, 0.3, 0.15, 0.05];
        let symbols = vec![0, 0, 1, 0, 2, 1, 0, 3, 0, 0, 1, 2];

        // Encode in REVERSE order (rANS is LIFO)
        let mut enc = RansEncoder::new();
        let cdf_table = quantize_pdf_to_rans_cdf(&pdf);
        for &s in symbols.iter().rev() {
            let cdf = cdf_for_symbol(&cdf_table, s);
            enc.encode(&cdf);
        }
        let encoded = enc.finish();

        // Decode in FORWARD order
        let mut dec = RansDecoder::new(&encoded).unwrap();
        for &expected in &symbols {
            let got = dec.decode(&cdf_table).unwrap();
            assert_eq!(got, expected, "Symbol mismatch");
        }
    }

    #[test]
    fn test_cdf_quantization() {
        let pdf = vec![0.25, 0.25, 0.25, 0.25];
        let cdf = quantize_pdf_to_rans_cdf(&pdf);

        assert_eq!(cdf[0], 0);
        assert_eq!(cdf[4], ANS_TOTAL);

        // Check roughly equal spacing
        for i in 1..4 {
            let delta = cdf[i] - cdf[i - 1];
            assert!(delta > 0);
        }
    }

    #[test]
    fn test_extreme_probabilities() {
        // Very skewed distribution
        let pdf = vec![0.99, 0.005, 0.003, 0.002];
        let symbols = vec![0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 3];

        // Encode in REVERSE order (rANS is LIFO)
        let mut enc = RansEncoder::new();
        let cdf_table = quantize_pdf_to_rans_cdf(&pdf);
        for &s in symbols.iter().rev() {
            let cdf = cdf_for_symbol(&cdf_table, s);
            enc.encode(&cdf);
        }
        let encoded = enc.finish();

        // Decode in FORWARD order
        let mut dec = RansDecoder::new(&encoded).unwrap();
        for &expected in &symbols {
            let got = dec.decode(&cdf_table).unwrap();
            assert_eq!(got, expected);
        }
    }

    #[test]
    fn test_blocked_rans_roundtrip_across_block_boundary() {
        let pdf = vec![0.5, 0.25, 0.125, 0.125];
        let cdf = quantize_pdf_to_rans_cdf(&pdf);
        let symbols: Vec<usize> = (0..(BLOCK_SIZE + 17)).map(|i| i % pdf.len()).collect();

        let mut enc = BlockedRansEncoder::new();
        for &sym in &symbols {
            enc.encode(cdf_for_symbol(&cdf, sym));
        }
        let blocks = enc.finish();
        let block_refs: Vec<&[u8]> = blocks.iter().map(Vec::as_slice).collect();

        let mut dec = BlockedRansDecoder::new(block_refs, symbols.len()).unwrap();
        for &expected in &symbols {
            let got = dec.decode(&cdf).unwrap();
            assert_eq!(got, expected, "blocked rANS mismatch at symbol {expected}");
        }
    }
}