zexc 1.2.1

zex native lossless compressor — CLI zexc, library zexc, files *.zex
Documentation
//! ZEX block structure.
//!
//! Each block:
//! ```text
//! ┌──────────┬────────────┬─────────────┬──────────────┐
//! │ type:u8  │ unc_size   │ comp_size   │ payload…     │
//! │          │ u32 LE     │ u32 LE      │ comp_size B  │
//! └──────────┴────────────┴─────────────┴──────────────┘
//! ```
//!
//! Payload for [`BlockType::Zex`] is the **native ZEX algorithm** bitstream
//! (see `algorithms::zex_native`) — not LZ4 and not Zstd wire format.

use crate::{Error, Result};
#[cfg(feature = "std")]
use std::io::{Read, Write};

/// Size of the on-wire block header (type + unc + comp).
pub const BLOCK_HEADER_SIZE: usize = 1 + 4 + 4;

/// Block storage type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum BlockType {
    /// Uncompressed raw bytes (incompressible / tiny).
    Raw = 0,
    /// Native ZEX algorithm payload.
    Zex = 1,
    /// End-of-frame marker (no payload).
    End = 0xFF,
}

impl BlockType {
    /// Parse from wire byte.
    pub fn from_u8(v: u8) -> Result<Self> {
        match v {
            0 => Ok(Self::Raw),
            1 => Ok(Self::Zex),
            // Legacy values from early hybrid prototypes — rejected cleanly.
            2 | 3 => Err(Error::CorruptBlock(
                "legacy lz4/zstd block type (unsupported; re-compress with native ZEX)".into(),
            )),
            0xFF => Ok(Self::End),
            other => Err(Error::CorruptBlock(format!(
                "unknown block type {other:#x}"
            ))),
        }
    }

    /// Display name.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Raw => "raw",
            Self::Zex => "zex",
            Self::End => "end",
        }
    }
}

/// On-wire block header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlockHeader {
    /// Compression type of the payload.
    pub block_type: BlockType,
    /// Uncompressed size of this block's content.
    pub uncompressed_size: u32,
    /// Compressed payload size in bytes.
    pub compressed_size: u32,
}

impl BlockHeader {
    /// End-of-frame sentinel.
    pub fn end() -> Self {
        Self {
            block_type: BlockType::End,
            uncompressed_size: 0,
            compressed_size: 0,
        }
    }

    /// `std`-only streaming twin of [`Self::to_bytes`], for
    /// [`crate::core::stream`]'s incremental `Write`-based encoder.
    #[cfg(feature = "std")]
    pub fn write_to<W: Write>(&self, out: &mut W) -> Result<()> {
        out.write_all(&self.to_bytes())?;
        Ok(())
    }

    /// `std`-only streaming twin of [`Self::from_bytes`], for
    /// [`crate::core::stream`]'s incremental `Read`-based decoder.
    #[cfg(feature = "std")]
    pub fn read_from<R: Read>(inp: &mut R) -> Result<Self> {
        let mut buf = [0u8; BLOCK_HEADER_SIZE];
        inp.read_exact(&mut buf)?;
        Self::from_bytes(&buf)
    }

    /// Parse from a fixed-size byte slice — `no_std`-safe, no I/O trait
    /// needed.
    pub fn from_bytes(buf: &[u8]) -> Result<Self> {
        if buf.len() < BLOCK_HEADER_SIZE {
            return Err(Error::CorruptBlock(format!(
                "block header buffer too short: {} < {BLOCK_HEADER_SIZE}",
                buf.len()
            )));
        }
        let block_type = BlockType::from_u8(buf[0])?;
        let uncompressed_size = u32::from_le_bytes(buf[1..5].try_into().unwrap());
        let compressed_size = u32::from_le_bytes(buf[5..9].try_into().unwrap());
        Ok(Self {
            block_type,
            uncompressed_size,
            compressed_size,
        })
    }

    /// Encode to fixed buffer.
    pub fn to_bytes(self) -> [u8; BLOCK_HEADER_SIZE] {
        let mut b = [0u8; BLOCK_HEADER_SIZE];
        b[0] = self.block_type as u8;
        b[1..5].copy_from_slice(&self.uncompressed_size.to_le_bytes());
        b[5..9].copy_from_slice(&self.compressed_size.to_le_bytes());
        b
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(feature = "std")]
    fn block_header_roundtrip() {
        let h = BlockHeader {
            block_type: BlockType::Zex,
            uncompressed_size: 65536,
            compressed_size: 12000,
        };
        let bytes = h.to_bytes();
        let p = BlockHeader::read_from(&mut &bytes[..]).unwrap();
        assert_eq!(p, h);
    }

    #[test]
    fn block_header_roundtrip_no_std() {
        let h = BlockHeader {
            block_type: BlockType::Zex,
            uncompressed_size: 65536,
            compressed_size: 12000,
        };
        let bytes = h.to_bytes();
        let p = BlockHeader::from_bytes(&bytes).unwrap();
        assert_eq!(p, h);
    }
}