Skip to main content

dsi_bitstream/codes/
omega.rs

1/*
2 * SPDX-FileCopyrightText: 2024 Tommaso Fontana
3 * SPDX-FileCopyrightText: 2025 Sebastiano Vigna
4 *
5 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
6 */
7
8//! Elias ω code.
9//!
10//! Elias [γ](super::gamma) and [δ](super::delta) codes encode a number *n* by
11//! storing the binary representation of *n* + 1, with the most significant bit
12//! removed, prefixed by its length in unary or [γ](super::gamma) code,
13//! respectively. Thus, [δ](super::delta) can be seen as adding one level of
14//! recursion in the length representation with respect to [γ](super::gamma).
15//! The ω code encodes the length of the binary representation of *n* + 1
16//! recursively.
17//!
18//! The implied distribution for the ω code is difficult to write analytically,
19//! but essentially it is as close as possible to ≈ 1/*x* (as there is no code
20//! for that distribution).
21//!
22//! The supported range is [0 . . 2⁶⁴ – 1).
23//!
24//! For the ω code it is easier to describe the format of a codeword, rather
25//! than the encoding algorithm.
26//!
27//! A codeword is given by the concatenation of blocks *b*₀ *b*₁ …  *b*ₙ `0`,
28//! where each block *b*ᵢ is a binary string starting with `1` and *b*₀ = `10`
29//! or `11`. One can interpret the highest bit of each block as a continuation
30//! bit, and the last `0` as a terminator of the code.
31//!
32//! The condition for a valid codeword is that the value represented by each
33//! block, incremented by one, is the length of the following block, except for
34//! the last block.
35//!
36//! The value associated with a codeword is 0 if the code is `0`, and otherwise
37//! the value of the last block, decremented by one.
38//!
39//! For example, `1110110`, which is formed by the blocks `11`, `1011`, and `0`,
40//! represents the number 10.
41//!
42//! As discussed in the [codes module documentation](crate::codes), to make the
43//! code readable in the little-endian case, rather than reversing the bits of
44//! the blocks, which would be expensive, we simply rotate by one on the left
45//! each block, with the result that the most significant bit of the block is
46//! now the first bit in the stream, making it possible to check for the
47//! presence of a continuation bit. For example, in the little-endian case, the
48//! code for 10 is `0011111`, which is formed by the blocks `11`, `0111`, and
49//! `0`.
50//!
51//! # Table-Based Optimization
52//!
53//! Unlike [γ](super::gamma), [δ](super::delta), and [ζ](super::zeta) codes, ω
54//! codes use a special optimization for partial decoding. Due to the recursive
55//! nature of ω codes, when a complete codeword cannot be read from the table
56//! the table still provides partial information about the blocks that were
57//! successfully decoded. This partial state is used to continue decoding
58//! efficiently, avoiding re-reading the initial blocks.
59//!
60//! # References
61//!
62//! Peter Elias. “[Universal codeword sets and representations of the
63//! integers](https://doi.org/10.1109/TIT.1975.1055349)”. IEEE Transactions on
64//! Information Theory, 21(2):194–203, March 1975.
65
66use crate::codes::omega_tables;
67use crate::traits::*;
68use num_primitive::PrimitiveNumber;
69
70/// Returns the length of the ω code for `n`.
71#[must_use]
72#[inline(always)]
73pub fn len_omega_param<const USE_TABLE: bool>(n: u64) -> usize {
74    debug_assert!(n < u64::MAX);
75    if USE_TABLE {
76        // We cannot use .get() here because n is a u64
77        if n < omega_tables::LEN.len() as u64 {
78            return omega_tables::LEN[n as usize] as usize;
79        }
80    }
81    recursive_len(n + 1)
82}
83
84/// Returns the length of the ω code for `n`, using
85/// a default value for `USE_TABLE`.
86#[must_use]
87#[inline(always)]
88pub fn len_omega(n: u64) -> usize {
89    len_omega_param::<true>(n)
90}
91
92const fn recursive_len(n: u64) -> usize {
93    if n <= 1 {
94        return 1;
95    }
96    let λ = n.ilog2() as u64;
97    recursive_len(λ) + λ as usize + 1
98}
99
100/// Trait for reading ω codes.
101///
102/// This is the trait you should usually pull into scope to read ω codes.
103pub trait OmegaRead<E: Endianness>: BitRead<E> {
104    fn read_omega(&mut self) -> Result<u64, Self::Error>;
105}
106
107/// Parametric trait for reading ω codes.
108///
109/// This trait is more general than [`OmegaRead`], as it makes it possible
110/// to specify how to use tables using const parameters.
111///
112/// We provide an implementation of this trait for [`BitRead`]. An implementation
113/// of [`OmegaRead`] using default values is usually provided exploiting the
114/// [`crate::codes::params::ReadParams`] mechanism.
115pub trait OmegaReadParam<E: Endianness>: BitRead<E> {
116    fn read_omega_param<const USE_TABLE: bool>(&mut self) -> Result<u64, Self::Error>;
117}
118
119/// Default, internal non-table based implementation that works
120/// for any endianness.
121#[inline(always)]
122fn default_read_omega<E: Endianness, B: BitRead<E>>(backend: &mut B) -> Result<u64, B::Error> {
123    read_omega_from_state::<E, B>(backend, 1)
124}
125
126/// Internal implementation that continues reading from a given state.
127///
128/// This is used both by the default implementation (starting from state n=1)
129/// and by the table-accelerated version (continuing from partial state).
130/// The bits have already been skipped by the caller.
131#[inline(always)]
132fn read_omega_from_state<E: Endianness, B: BitRead<E>>(
133    backend: &mut B,
134    mut n: u64,
135) -> Result<u64, B::Error> {
136    loop {
137        let bit: u64 = backend.peek_bits(1)?.as_to();
138        if bit == 0 {
139            backend.skip_bits_after_peek(1);
140            return Ok(n - 1);
141        }
142
143        let λ = n;
144        n = backend.read_bits(λ as usize + 1)?;
145
146        if E::IS_LITTLE {
147            // Little-endian case: rotate right the lower λ + 1 bits (the lowest
148            // bit is a one) to reverse the rotation performed when writing
149            n = (n >> 1) | (1 << λ);
150        }
151    }
152}
153
154impl<B: BitRead<BE>> OmegaReadParam<BE> for B {
155    #[inline(always)]
156    fn read_omega_param<const USE_TABLE: bool>(&mut self) -> Result<u64, Self::Error> {
157        const {
158            if USE_TABLE {
159                omega_tables::check_read_table(B::PEEK_BITS)
160            }
161        }
162        if USE_TABLE {
163            let (len_with_flag, value) = omega_tables::read_table_be(self);
164            if len_with_flag > 0 {
165                // Complete code - bits already skipped in read_table
166                return Ok(value);
167            } else if len_with_flag < 0 {
168                // Partial code - bits already skipped in read_table, continue from partial_n
169                return read_omega_from_state::<BE, _>(self, value);
170            }
171            // len_with_flag == 0: not enough bits, fall through
172        }
173        default_read_omega(self)
174    }
175}
176
177impl<B: BitRead<LE>> OmegaReadParam<LE> for B {
178    #[inline(always)]
179    fn read_omega_param<const USE_TABLE: bool>(&mut self) -> Result<u64, Self::Error> {
180        const {
181            if USE_TABLE {
182                omega_tables::check_read_table(B::PEEK_BITS)
183            }
184        }
185        if USE_TABLE {
186            let (len_with_flag, value) = omega_tables::read_table_le(self);
187            if len_with_flag > 0 {
188                // Complete code - bits already skipped in read_table
189                return Ok(value);
190            } else if len_with_flag < 0 {
191                // Partial code - bits already skipped in read_table, continue from partial_n
192                return read_omega_from_state::<LE, _>(self, value);
193            }
194            // len_with_flag == 0: not enough bits, fall through
195        }
196        default_read_omega(self)
197    }
198}
199
200/// Trait for writing ω codes.
201///
202/// This is the trait you should usually pull into scope to write ω codes.
203pub trait OmegaWrite<E: Endianness>: BitWrite<E> {
204    fn write_omega(&mut self, n: u64) -> Result<usize, Self::Error>;
205}
206
207/// Parametric trait for writing ω codes.
208///
209/// This trait is more general than [`OmegaWrite`], as it makes it possible
210/// to specify how to use tables using const parameters.
211///
212/// We provide an implementation of this trait for [`BitWrite`]. An implementation
213/// of [`OmegaWrite`] using default values is usually provided exploiting the
214/// [`crate::codes::params::WriteParams`] mechanism.
215pub trait OmegaWriteParam<E: Endianness>: BitWrite<E> {
216    fn write_omega_param<const USE_TABLE: bool>(&mut self, n: u64) -> Result<usize, Self::Error>;
217}
218
219impl<B: BitWrite<BE>> OmegaWriteParam<BE> for B {
220    #[inline(always)]
221    fn write_omega_param<const USE_TABLE: bool>(&mut self, n: u64) -> Result<usize, Self::Error> {
222        debug_assert!(n < u64::MAX);
223        if USE_TABLE {
224            if let Some(len) = omega_tables::write_table_be(self, n)? {
225                return Ok(len);
226            }
227        }
228        Ok(recursive_omega_write::<BE, _>(n + 1, self)? + self.write_bits(0, 1)?)
229    }
230}
231
232impl<B: BitWrite<LE>> OmegaWriteParam<LE> for B {
233    #[inline(always)]
234    fn write_omega_param<const USE_TABLE: bool>(&mut self, n: u64) -> Result<usize, Self::Error> {
235        debug_assert!(n < u64::MAX);
236        if USE_TABLE {
237            if let Some(len) = omega_tables::write_table_le(self, n)? {
238                return Ok(len);
239            }
240        }
241        Ok(recursive_omega_write::<LE, _>(n + 1, self)? + self.write_bits(0, 1)?)
242    }
243}
244
245#[inline(always)]
246fn recursive_omega_write<E: Endianness, B: BitWrite<E>>(
247    mut n: u64,
248    writer: &mut B,
249) -> Result<usize, B::Error> {
250    if n <= 1 {
251        return Ok(0);
252    }
253    let λ = n.ilog2();
254    if E::IS_LITTLE {
255        #[cfg(feature = "checks")]
256        {
257            // Clean up after the lowest λ bits in case checks are enabled
258            n &= u64::MAX >> (u64::BITS - λ);
259        }
260        // Little-endian case: rotate left the lower λ + 1 bits (the bit in
261        // position λ is a one) so that the lowest bit can be peeked to find the
262        // block.
263        n = (n << 1) | 1;
264    }
265    Ok(recursive_omega_write::<E, _>(λ as u64, writer)? + writer.write_bits(n, λ as usize + 1)?)
266}
267
268#[cfg(test)]
269mod tests {
270    use crate::prelude::*;
271
272    #[test]
273    #[allow(clippy::unusual_byte_groupings)]
274    fn test_omega() {
275        for (value, expected_be, expected_le) in [
276            (0, 0, 0),
277            (1, 0b10_0 << (64 - 3), 0b0_01),
278            (2, 0b11_0 << (64 - 3), 0b0_11),
279            (3, 0b10_100_0 << (64 - 6), 0b0_001_01),
280            (4, 0b10_101_0 << (64 - 6), 0b0_011_01),
281            (5, 0b10_110_0 << (64 - 6), 0b0_101_01),
282            (6, 0b10_111_0 << (64 - 6), 0b0_111_01),
283            (7, 0b11_1000_0 << (64 - 7), 0b0_0001_11),
284            (15, 0b10_100_10000_0 << (64 - 11), 0b0_00001_001_01),
285            (99, 0b10_110_1100100_0 << (64 - 13), 0b0_1001001_101_01),
286            (
287                999,
288                0b11_1001_1111101000_0 << (64 - 17),
289                0b0_1111010001_0011_11,
290            ),
291            (
292                999_999,
293                0b10_100_10011_11110100001001000000_0 << (64 - 31),
294                0b0_11101000010010000001_00111_001_01,
295            ),
296        ] {
297            let mut data = [0_u64];
298            let mut writer = <BufBitWriter<BE, _>>::new(MemWordWriterSlice::new(&mut data));
299            writer.write_omega(value).unwrap();
300            drop(writer);
301            assert_eq!(
302                data[0].to_be(),
303                expected_be,
304                "\nfor value: {}\ngot: {:064b}\nexp: {:064b}\n",
305                value,
306                data[0].to_be(),
307                expected_be,
308            );
309
310            let mut data = [0_u64];
311            let mut writer = <BufBitWriter<LE, _>>::new(MemWordWriterSlice::new(&mut data));
312            writer.write_omega(value).unwrap();
313            drop(writer);
314            assert_eq!(
315                data[0].to_le(),
316                expected_le,
317                "\nfor value: {}\ngot: {:064b}\nexp: {:064b}\n",
318                value,
319                data[0].to_le(),
320                expected_le,
321            );
322        }
323    }
324}