dsi-bitstream 0.9.2

A Rust implementation of read/write bit streams supporting several types of instantaneous codes
Documentation
/*
 * SPDX-FileCopyrightText: 2023 Sebastiano Vigna
 *
 * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
 */

//! Exponential Golomb codes.
//!
//! Exponential Golomb codes are a variant of Golomb codes with power-of-two
//! modulus (i.e., [Rice codes](super::rice)) in which the prefix is written
//! using [Elias γ code](super::gamma) instead of unary code. More precisely,
//! the exponential Golomb code with parameter *k* ≥ 0 of a natural number *x*
//! is given by ⌊*x* / 2*ᵏ*⌋ in [γ code](super::gamma) followed by *x* mod 2*ᵏ*
//! in binary *k*-bit representation.
//!
//! The implied distribution of an exponential Golomb code with parameter *k* is
//! ≈ 2²*ᵏ*/2*x*².
//!
//! Note that the exponential Golomb code for *k* = 0 is exactly the [γ
//! code](super::gamma).
//!
//! The supported range is [0 . . 2⁶⁴ – 1) for *k* = 0 and [0 . . 2⁶⁴) for *k*
//! in [1 . . 64).
//!
//! Exponential Golomb codes are used in the [H.264
//! (MPEG-4)](https://en.wikipedia.org/wiki/Advanced_Video_Coding) and
//! [H.265](https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding)
//! standards.

use super::gamma::{GammaRead, GammaWrite, len_gamma};
use crate::traits::*;

/// Returns the length of the exponential Golomb code for `n` with parameter `k`.
#[must_use]
#[inline(always)]
pub fn len_exp_golomb(n: u64, k: usize) -> usize {
    debug_assert!(k < 64);
    len_gamma(n >> k) + k
}

/// Trait for reading exponential Golomb codes.
pub trait ExpGolombRead<E: Endianness>: GammaRead<E> {
    #[inline(always)]
    fn read_exp_golomb(&mut self, k: usize) -> Result<u64, Self::Error> {
        debug_assert!(k < 64);
        Ok((self.read_gamma()? << k) + self.read_bits(k)?)
    }
}

/// Trait for writing exponential Golomb codes.
pub trait ExpGolombWrite<E: Endianness>: GammaWrite<E> {
    #[inline(always)]
    fn write_exp_golomb(&mut self, n: u64, k: usize) -> Result<usize, Self::Error> {
        debug_assert!(k < 64);
        let mut written_bits = self.write_gamma(n >> k)?;
        #[cfg(feature = "checks")]
        {
            // Clean up n in case checks are enabled
            let n = n & (1_u128 << k).wrapping_sub(1) as u64;
            written_bits += self.write_bits(n, k)?;
        }
        #[cfg(not(feature = "checks"))]
        {
            written_bits += self.write_bits(n, k)?;
        }
        Ok(written_bits)
    }
}

impl<E: Endianness, B: GammaRead<E>> ExpGolombRead<E> for B {}
impl<E: Endianness, B: GammaWrite<E>> ExpGolombWrite<E> for B {}