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, prelude::*};
67use num_traits::AsPrimitive;
68
69/// Returns the length of the ω code for `n`.
70#[must_use]
71#[inline(always)]
72pub fn len_omega_param<const USE_TABLE: bool>(n: u64) -> usize {
73 debug_assert!(n < u64::MAX);
74 if USE_TABLE {
75 if let Some(len) = omega_tables::LEN.get(n as usize) {
76 return *len as usize;
77 }
78 }
79 recursive_len(n + 1)
80}
81
82/// Returns the length of the ω code for `n`, using
83/// a default value for `USE_TABLE`.
84#[must_use]
85#[inline(always)]
86pub fn len_omega(n: u64) -> usize {
87 len_omega_param::<true>(n)
88}
89
90const fn recursive_len(n: u64) -> usize {
91 if n <= 1 {
92 return 1;
93 }
94 let λ = n.ilog2() as u64;
95 recursive_len(λ) + λ as usize + 1
96}
97
98/// Trait for reading ω codes.
99///
100/// This is the trait you should usually pull into scope to read ω codes.
101pub trait OmegaRead<E: Endianness>: BitRead<E> {
102 fn read_omega(&mut self) -> Result<u64, Self::Error>;
103}
104
105/// Parametric trait for reading ω codes.
106///
107/// This trait is more general than [`OmegaRead`], as it makes it possible
108/// to specify how to use tables using const parameters.
109///
110/// We provide an implementation of this trait for [`BitRead`]. An implementation
111/// of [`OmegaRead`] using default values is usually provided exploiting the
112/// [`crate::codes::params::ReadParams`] mechanism.
113pub trait OmegaReadParam<E: Endianness>: BitRead<E> {
114 fn read_omega_param<const USE_TABLE: bool>(&mut self) -> Result<u64, Self::Error>;
115}
116
117/// Default, internal non-table based implementation that works
118/// for any endianness.
119#[inline(always)]
120fn default_read_omega<E: Endianness, B: BitRead<E>>(backend: &mut B) -> Result<u64, B::Error> {
121 read_omega_from_state::<E, B>(backend, 1)
122}
123
124/// Internal implementation that continues reading from a given state.
125///
126/// This is used both by the default implementation (starting from state n=1)
127/// and by the table-accelerated version (continuing from partial state).
128/// The bits have already been skipped by the caller.
129#[inline(always)]
130fn read_omega_from_state<E: Endianness, B: BitRead<E>>(
131 backend: &mut B,
132 mut n: u64,
133) -> Result<u64, B::Error> {
134 loop {
135 let bit = backend.peek_bits(1)?.as_();
136 if bit == 0 {
137 backend.skip_bits_after_peek(1);
138 return Ok(n - 1);
139 }
140
141 let λ = n;
142 n = backend.read_bits(λ as usize + 1)?;
143
144 if E::IS_LITTLE {
145 // Little-endian case: rotate right the lower λ + 1 bits (the lowest
146 // bit is a one) to reverse the rotation performed when writing
147 n = (n >> 1) | (1 << λ);
148 }
149 }
150}
151
152impl<B: BitRead<BE>> OmegaReadParam<BE> for B {
153 #[inline(always)]
154 fn read_omega_param<const USE_TABLE: bool>(&mut self) -> Result<u64, Self::Error> {
155 const {
156 if USE_TABLE {
157 omega_tables::check_read_table(B::PEEK_BITS)
158 }
159 }
160 if USE_TABLE {
161 let (len_with_flag, value) = omega_tables::read_table_be(self);
162 if len_with_flag > 0 {
163 // Complete code - bits already skipped in read_table
164 return Ok(value);
165 } else if len_with_flag < 0 {
166 // Partial code - bits already skipped in read_table, continue from partial_n
167 return read_omega_from_state::<BE, _>(self, value);
168 }
169 // len_with_flag == 0: not enough bits, fall through
170 }
171 default_read_omega(self)
172 }
173}
174
175impl<B: BitRead<LE>> OmegaReadParam<LE> for B {
176 #[inline(always)]
177 fn read_omega_param<const USE_TABLE: bool>(&mut self) -> Result<u64, Self::Error> {
178 const {
179 if USE_TABLE {
180 omega_tables::check_read_table(B::PEEK_BITS)
181 }
182 }
183 if USE_TABLE {
184 let (len_with_flag, value) = omega_tables::read_table_le(self);
185 if len_with_flag > 0 {
186 // Complete code - bits already skipped in read_table
187 return Ok(value);
188 } else if len_with_flag < 0 {
189 // Partial code - bits already skipped in read_table, continue from partial_n
190 return read_omega_from_state::<LE, _>(self, value);
191 }
192 // len_with_flag == 0: not enough bits, fall through
193 }
194 default_read_omega(self)
195 }
196}
197
198/// Trait for writing ω codes.
199///
200/// This is the trait you should usually pull into scope to write ω codes.
201pub trait OmegaWrite<E: Endianness>: BitWrite<E> {
202 fn write_omega(&mut self, n: u64) -> Result<usize, Self::Error>;
203}
204
205/// Parametric trait for writing ω codes.
206///
207/// This trait is more general than [`OmegaWrite`], as it makes it possible
208/// to specify how to use tables using const parameters.
209///
210/// We provide an implementation of this trait for [`BitWrite`]. An implementation
211/// of [`OmegaWrite`] using default values is usually provided exploiting the
212/// [`crate::codes::params::WriteParams`] mechanism.
213pub trait OmegaWriteParam<E: Endianness>: BitWrite<E> {
214 fn write_omega_param<const USE_TABLE: bool>(&mut self, n: u64) -> Result<usize, Self::Error>;
215}
216
217impl<B: BitWrite<BE>> OmegaWriteParam<BE> for B {
218 #[inline(always)]
219 fn write_omega_param<const USE_TABLE: bool>(&mut self, n: u64) -> Result<usize, Self::Error> {
220 debug_assert!(n < u64::MAX);
221 if USE_TABLE {
222 if let Some(len) = omega_tables::write_table_be(self, n)? {
223 return Ok(len);
224 }
225 }
226 Ok(recursive_omega_write::<BE, _>(n + 1, self)? + self.write_bits(0, 1)?)
227 }
228}
229
230impl<B: BitWrite<LE>> OmegaWriteParam<LE> for B {
231 #[inline(always)]
232 fn write_omega_param<const USE_TABLE: bool>(&mut self, n: u64) -> Result<usize, Self::Error> {
233 debug_assert!(n < u64::MAX);
234 if USE_TABLE {
235 if let Some(len) = omega_tables::write_table_le(self, n)? {
236 return Ok(len);
237 }
238 }
239 Ok(recursive_omega_write::<LE, _>(n + 1, self)? + self.write_bits(0, 1)?)
240 }
241}
242
243#[inline(always)]
244fn recursive_omega_write<E: Endianness, B: BitWrite<E>>(
245 mut n: u64,
246 writer: &mut B,
247) -> Result<usize, B::Error> {
248 if n <= 1 {
249 return Ok(0);
250 }
251 let λ = n.ilog2();
252 if E::IS_LITTLE {
253 #[cfg(feature = "checks")]
254 {
255 // Clean up after the lowest λ bits in case checks are enabled
256 n &= u64::MAX >> (u64::BITS - λ);
257 }
258 // Little-endian case: rotate left the lower λ + 1 bits (the bit in
259 // position λ is a one) so that the lowest bit can be peeked to find the
260 // block.
261 n = (n << 1) | 1;
262 }
263 Ok(recursive_omega_write::<E, _>(λ as u64, writer)? + writer.write_bits(n, λ as usize + 1)?)
264}
265
266#[cfg(test)]
267mod tests {
268 use crate::prelude::*;
269
270 #[test]
271 #[allow(clippy::unusual_byte_groupings)]
272 fn test_omega() {
273 for (value, expected_be, expected_le) in [
274 (0, 0, 0),
275 (1, 0b10_0 << (64 - 3), 0b0_01),
276 (2, 0b11_0 << (64 - 3), 0b0_11),
277 (3, 0b10_100_0 << (64 - 6), 0b0_001_01),
278 (4, 0b10_101_0 << (64 - 6), 0b0_011_01),
279 (5, 0b10_110_0 << (64 - 6), 0b0_101_01),
280 (6, 0b10_111_0 << (64 - 6), 0b0_111_01),
281 (7, 0b11_1000_0 << (64 - 7), 0b0_0001_11),
282 (15, 0b10_100_10000_0 << (64 - 11), 0b0_00001_001_01),
283 (99, 0b10_110_1100100_0 << (64 - 13), 0b0_1001001_101_01),
284 (
285 999,
286 0b11_1001_1111101000_0 << (64 - 17),
287 0b0_1111010001_0011_11,
288 ),
289 (
290 999_999,
291 0b10_100_10011_11110100001001000000_0 << (64 - 31),
292 0b0_11101000010010000001_00111_001_01,
293 ),
294 ] {
295 let mut data = [0_u64];
296 let mut writer = <BufBitWriter<BE, _>>::new(MemWordWriterSlice::new(&mut data));
297 writer.write_omega(value).unwrap();
298 drop(writer);
299 assert_eq!(
300 data[0].to_be(),
301 expected_be,
302 "\nfor value: {}\ngot: {:064b}\nexp: {:064b}\n",
303 value,
304 data[0].to_be(),
305 expected_be,
306 );
307
308 let mut data = [0_u64];
309 let mut writer = <BufBitWriter<LE, _>>::new(MemWordWriterSlice::new(&mut data));
310 writer.write_omega(value).unwrap();
311 drop(writer);
312 assert_eq!(
313 data[0].to_le(),
314 expected_le,
315 "\nfor value: {}\ngot: {:064b}\nexp: {:064b}\n",
316 value,
317 data[0].to_le(),
318 expected_le,
319 );
320 }
321 }
322}