#![forbid(unsafe_code)]
pub mod header;
use crate::error::DecompressError;
pub const ZSTD_MAGIC: u32 = 0xFD2F_B528;
pub const MIN_FRAME_HEADER_SIZE: usize = 2;
pub const MAX_BLOCK_SIZE: usize = 128 * 1024;
pub const MAX_WINDOW_SIZE: u64 = 1 << 27;
pub fn find_frame_compressed_size(input: &[u8]) -> Result<usize, DecompressError> {
if input.len() < 4 {
return Err(DecompressError::InputExhausted);
}
let magic = u32::from_le_bytes([input[0], input[1], input[2], input[3]]);
if (magic & 0xFFFF_FFF0) == 0x184D_2A50 {
if input.len() < 8 {
return Err(DecompressError::InputExhausted);
}
let size = u32::from_le_bytes([input[4], input[5], input[6], input[7]]) as usize;
let total = size.checked_add(8).ok_or(DecompressError::InputExhausted)?;
return if total <= input.len() {
Ok(total)
} else {
Err(DecompressError::InputExhausted)
};
}
if magic != ZSTD_MAGIC {
return Err(DecompressError::BadMagic);
}
let descriptor = *input.get(4).ok_or(DecompressError::InputExhausted)?;
let single_segment = descriptor & 0x20 != 0;
let header_size = 5
+ usize::from(!single_segment)
+ [0, 1, 2, 4][usize::from(descriptor & 0x03)]
+ match descriptor >> 6 {
0 => usize::from(single_segment),
1 => 2,
2 => 4,
_ => 8,
};
if input.len() < header_size {
return Err(DecompressError::InputExhausted);
}
let header = header::parse_frame_header(&input[..header_size])?;
let mut pos = header.header_size;
loop {
let block = crate::block::parse_block_header(input.get(pos..).unwrap_or(&[]))?;
let size = block.block_size as usize;
if size > MAX_BLOCK_SIZE {
return Err(DecompressError::BlockTooLarge);
}
let body = match block.block_type {
crate::block::BlockType::Rle => 1,
_ => size,
};
pos += 3 + body;
if pos > input.len() {
return Err(DecompressError::InputExhausted);
}
if block.last_block {
break;
}
}
if header.content_checksum {
pos += 4;
if pos > input.len() {
return Err(DecompressError::InputExhausted);
}
}
Ok(pos)
}