use crate::{Error, Result};
#[cfg(feature = "std")]
use std::io::{Read, Write};
pub const BLOCK_HEADER_SIZE: usize = 1 + 4 + 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum BlockType {
Raw = 0,
Zex = 1,
End = 0xFF,
}
impl BlockType {
pub fn from_u8(v: u8) -> Result<Self> {
match v {
0 => Ok(Self::Raw),
1 => Ok(Self::Zex),
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}"
))),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Raw => "raw",
Self::Zex => "zex",
Self::End => "end",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlockHeader {
pub block_type: BlockType,
pub uncompressed_size: u32,
pub compressed_size: u32,
}
impl BlockHeader {
pub fn end() -> Self {
Self {
block_type: BlockType::End,
uncompressed_size: 0,
compressed_size: 0,
}
}
#[cfg(feature = "std")]
pub fn write_to<W: Write>(&self, out: &mut W) -> Result<()> {
out.write_all(&self.to_bytes())?;
Ok(())
}
#[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)
}
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,
})
}
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);
}
}