euv-docs 0.48.1

Cross-platform documentation viewer and static site generator powered by euv and euv-ui.
Documentation
use super::*;

/// Human-readable diagnostic formatting for `DocsCodecError`.
impl fmt::Display for DocsCodecError {
    /// Formats a descriptive error string for build logs and boot diagnostics.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Error variant reference.
    /// - `&mut fmt::Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting result.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BadMagic => write!(f, "{CODEC_ERR_BAD_MAGIC}"),
            Self::UnsupportedVersion(version) => write!(f, "{CODEC_ERR_VERSION}: {version}"),
            Self::Truncated => write!(f, "{CODEC_ERR_TRUNCATED}"),
            Self::InvalidCodeLengths => write!(f, "{CODEC_ERR_CODE_LENGTHS}"),
            Self::InvalidSymbol => write!(f, "{CODEC_ERR_SYMBOL}"),
            Self::InvalidDistance => write!(f, "{CODEC_ERR_DISTANCE}"),
            Self::LengthMismatch => write!(f, "{CODEC_ERR_LENGTH}"),
            Self::PageCountMismatch => write!(f, "{CODEC_ERR_PAGE_COUNT}"),
            Self::InvalidPayload(reason) => write!(f, "{CODEC_ERR_PAYLOAD}: {reason}"),
        }
    }
}

/// Bit-level streaming helpers for `CodecBitWriter`.
impl CodecBitWriter {
    /// Creates an empty bit writer preallocated for approximately `capacity` output bytes.
    ///
    /// # Arguments
    ///
    /// - `usize` - Estimated output byte capacity.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized bit writer.
    pub(crate) fn with_capacity(capacity: usize) -> Self {
        Self {
            bytes: Vec::with_capacity(capacity),
            bit_buf: 0,
            bit_count: 0,
        }
    }

    /// Appends the lowest `count` bits of `bits` in LSB-first order.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable bit writer reference.
    /// - `u64` - Bit payload (only lowest `count` bits are used).
    /// - `u32` - Number of bits to append (`0..=32`).
    pub(crate) fn write_bits(&mut self, bits: u64, count: u32) {
        if count == 0 {
            return;
        }
        let next_buf: u64 = self.get_bit_buf() | (bits << self.get_bit_count());
        let mut next_count: u32 = self.get_bit_count() + count;
        let mut cur_buf: u64 = next_buf;
        while next_count >= 8 {
            self.get_mut_bytes().push((cur_buf & 0xFF) as u8);
            cur_buf >>= 8;
            next_count -= 8;
        }
        self.set_bit_buf(cur_buf);
        self.set_bit_count(next_count);
    }

    /// Flushes any trailing partial byte padded with zero bits and returns the encoded byte vector.
    ///
    /// # Arguments
    ///
    /// - `Self` - Consumed bit writer.
    ///
    /// # Returns
    ///
    /// - `Vec<u8>` - Complete encoded byte stream.
    pub(crate) fn finish(mut self) -> Vec<u8> {
        if self.get_bit_count() > 0 {
            let tail: u8 = (self.get_bit_buf() & 0xFF) as u8;
            self.get_mut_bytes().push(tail);
            self.set_bit_buf(0);
            self.set_bit_count(0);
        }
        take(self.get_mut_bytes())
    }
}

/// Bit-level streaming helpers for `CodecBitReader`.
impl<'a> CodecBitReader<'a> {
    /// Creates a new bit reader positioned at byte offset `0` of `data`.
    ///
    /// # Arguments
    ///
    /// - `&'a [u8]` - Compressed byte slice positioned after the stream header.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized bit reader.
    pub(crate) fn from_slice(data: &'a [u8]) -> Self {
        Self {
            data,
            cursor: 0,
            bit_buf: 0,
            bit_count: 0,
        }
    }

    /// Refills the bit buffer from `data` until at least `CODEC_REFILL_THRESHOLD` bits are buffered or input ends.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable bit reader reference.
    pub(crate) fn refill(&mut self) {
        let slice: &[u8] = self.get_data();
        let mut pos: usize = self.get_cursor();
        let mut buf: u64 = self.get_bit_buf();
        let mut count: u32 = self.get_bit_count();
        while count <= CODEC_REFILL_THRESHOLD && pos < slice.len() {
            buf |= (slice[pos] as u64) << count;
            pos += 1;
            count += 8;
        }
        self.set_cursor(pos);
        self.set_bit_buf(buf);
        self.set_bit_count(count);
    }

    /// Reads exactly `count` bits in LSB-first order, failing with `DocsCodecError::Truncated` if unavailable.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable bit reader reference.
    /// - `u32` - Number of bits to read (`0..=32`).
    ///
    /// # Returns
    ///
    /// - `Result<u32, DocsCodecError>` - Extracted bit value or truncation error.
    pub(crate) fn read_bits(&mut self, count: u32) -> Result<u32, DocsCodecError> {
        if count == 0 {
            return Ok(0);
        }
        if self.get_bit_count() < count {
            self.refill();
            if self.get_bit_count() < count {
                return Err(DocsCodecError::Truncated);
            }
        }
        let mask: u64 = (1u64 << count) - 1;
        let value: u32 = (self.get_bit_buf() & mask) as u32;
        self.set_bit_buf(self.get_bit_buf() >> count);
        self.set_bit_count(self.get_bit_count() - count);
        Ok(value)
    }

    /// Consumes `count` already-peeked bits from the buffer.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable bit reader reference.
    /// - `u32` - Number of bits to drop.
    pub(crate) fn consume(&mut self, count: u32) {
        self.set_bit_buf(self.get_bit_buf() >> count);
        self.set_bit_count(self.get_bit_count() - count);
    }
}