euv-core 0.56.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Construction helpers for `ZstdFseTable`.
impl ZstdFseTable {
    /// Builds a 1-state constant RLE FSE table that always outputs `symbol` consuming 0 bits.
    ///
    /// # Arguments
    ///
    /// - `u8` - Constant symbol emitted on every step.
    ///
    /// # Returns
    ///
    /// - `Self` - Single-entry RLE FSE table.
    #[must_use]
    pub(crate) fn from_rle(symbol: u8) -> Self {
        Self {
            accuracy_log: 0,
            entries: vec![ZstdFseEntry::new(symbol, 0, 0)],
        }
    }

    /// Builds a flat FSE decoding table from a normalized RFC 8878 probability distribution.
    ///
    /// # Arguments
    ///
    /// - `&[i16]` - Normalized probability counts (`-1` means less-than-1 probability).
    /// - `u8` - Table accuracy log (`0..=9`).
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Ready flat FSE decoding table or distribution error.
    pub(crate) fn from_distribution(probs: &[i16], accuracy_log: u8) -> Result<Self, String> {
        let table_size: usize = 1usize << usize::from(accuracy_log);
        let table_mask: usize = table_size - 1;
        let step: usize = (table_size >> 1) + (table_size >> 3) + 3;
        let mut high_threshold: usize = table_size - 1;
        let mut symbols: Vec<u8> = vec![0u8; table_size];
        let mut symbol_next: Vec<u16> = vec![0u16; probs.len()];
        let mut total_prob: usize = 0;
        for (sym, &prob) in probs.iter().enumerate() {
            if prob == -1 {
                if high_threshold >= table_size {
                    return Err(ERR_BLEND_ZSTD_FSE.to_string());
                }
                symbols[high_threshold] = sym as u8;
                high_threshold = high_threshold.wrapping_sub(1);
                symbol_next[sym] = 1;
                total_prob += 1;
            } else if prob > 0 {
                symbol_next[sym] = prob as u16;
                total_prob += prob as usize;
            }
        }
        if total_prob != table_size {
            return Err(ERR_BLEND_ZSTD_FSE.to_string());
        }
        let mut pos: usize = 0;
        for (sym, &prob) in probs.iter().enumerate() {
            if prob <= 0 {
                continue;
            }
            for _ in 0..(prob as usize) {
                symbols[pos] = sym as u8;
                loop {
                    pos = (pos + step) & table_mask;
                    if high_threshold == usize::MAX || pos <= high_threshold {
                        break;
                    }
                }
            }
        }
        if pos != 0 {
            return Err(ERR_BLEND_ZSTD_FSE.to_string());
        }
        let mut entries: Vec<ZstdFseEntry> = Vec::with_capacity(table_size);
        for &sym_u8 in symbols.iter() {
            let sym: usize = usize::from(sym_u8);
            let next_state: u16 = symbol_next[sym];
            if next_state == 0 {
                return Err(ERR_BLEND_ZSTD_FSE.to_string());
            }
            symbol_next[sym] = next_state.saturating_add(1);
            let high_bit: u8 = (15u32.saturating_sub(next_state.leading_zeros())) as u8;
            let num_bits: u8 = accuracy_log.saturating_sub(high_bit);
            let baseline_full: usize =
                (usize::from(next_state) << usize::from(num_bits)).saturating_sub(table_size);
            entries.push(ZstdFseEntry::new(sym_u8, num_bits, baseline_full as u16));
        }
        Ok(Self {
            accuracy_log,
            entries,
        })
    }
}

/// Construction helpers for `ZstdFrameState`.
impl ZstdFrameState {
    /// Creates fresh per-frame decoder state with RFC 8878 initial repeat offsets `[1, 4, 8]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized per-frame Zstandard decoder state.
    #[must_use]
    pub(crate) fn new_frame() -> Self {
        Self {
            huffman: None,
            ll_table: None,
            of_table: None,
            ml_table: None,
            repeat_offsets: ZSTD_INITIAL_REPEAT_OFFSETS,
        }
    }
}

/// Reverse bitstream reader primitives for RFC 8878 Huffman and FSE decoding.
impl<'a> ZstdReverseBitReader<'a> {
    /// Initializes a reverse bitstream reader by locating the mandatory sentinel `1` bit in the final byte.
    ///
    /// # Arguments
    ///
    /// - `&'a [u8]` - Compressed bitstream slice terminated with a sentinel `1` bit.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Initialized reverse bit reader or framing error.
    pub(crate) fn new(data: &'a [u8]) -> Result<Self, String> {
        let last: u8 = *data
            .last()
            .ok_or_else(|| ERR_BLEND_ZSTD_TRUNCATED.to_string())?;
        if last == 0 {
            return Err(ERR_BLEND_ZSTD_FSE.to_string());
        }
        let padding_bits: usize = (last.leading_zeros() as usize) + 1;
        let total_bits: usize = data.len().saturating_mul(8).saturating_sub(padding_bits);
        Ok(Self {
            data,
            total_bits,
            bits_consumed: 0,
        })
    }

    /// Returns the number of unread bits remaining (`0` if exact end or overflowed).
    ///
    /// # Returns
    ///
    /// - `usize` - Remaining unread bit count.
    #[must_use]
    pub(crate) fn bits_remaining(&self) -> usize {
        self.get_total_bits()
            .saturating_sub(self.get_bits_consumed())
    }

    /// Returns `true` when consumption has passed `total_bits` (RFC 8878 `BIT_DStream_overflow`).
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the reader has overflowed past bit 0.
    #[must_use]
    pub(crate) fn is_overflow(&self) -> bool {
        self.get_bits_consumed() > self.get_total_bits()
    }

    /// Peeks `num_bits` MSB-first bits (`0..=32`), zero-padding past bit 0 when fewer bits remain.
    ///
    /// # Arguments
    ///
    /// - `u8` - Number of bits to peek (`0..=32`).
    ///
    /// # Returns
    ///
    /// - `u32` - Peeked bits aligned to the least-significant `num_bits` positions.
    #[must_use]
    pub(crate) fn peek_bits(&self, num_bits: u8) -> u32 {
        let count: usize = usize::from(num_bits);
        if count == 0 {
            return 0;
        }
        let consumed: usize = self.get_bits_consumed();
        let total: usize = self.get_total_bits();
        let bytes: &[u8] = self.get_data();
        let mut acc: u32 = 0;
        for step in 0..count {
            acc <<= 1;
            let bit_from_top: usize = consumed + step;
            if bit_from_top < total {
                let bit_index: usize = total - 1 - bit_from_top;
                let byte_val: u8 = bytes[bit_index >> 3];
                let bit_val: u32 = u32::from((byte_val >> (bit_index & 7)) & 1);
                acc |= bit_val;
            }
        }
        acc
    }

    /// Consumes and returns `num_bits` MSB-first bits (`0..=32`), zero-padding past bit 0 and recording overflow if past `total_bits`.
    ///
    /// # Arguments
    ///
    /// - `u8` - Number of bits to read (`0..=32`).
    ///
    /// # Returns
    ///
    /// - `u32` - Read bit value.
    pub(crate) fn read_bits(&mut self, num_bits: u8) -> u32 {
        let val: u32 = self.peek_bits(num_bits);
        let next: usize = self
            .get_bits_consumed()
            .saturating_add(usize::from(num_bits));
        let _: &mut Self = self.set_bits_consumed(next);
        val
    }

    /// Consumes `num_bits` bits after peeking.
    ///
    /// # Arguments
    ///
    /// - `u8` - Number of bits to advance.
    pub(crate) fn consume_bits(&mut self, num_bits: u8) {
        let next: usize = self
            .get_bits_consumed()
            .saturating_add(usize::from(num_bits));
        let _: &mut Self = self.set_bits_consumed(next);
    }
}