use crate::error::{Error, Result};
use crate::varint;
pub(crate) const MAGIC_CHUNKS: u32 = 0x85BD_40DD;
pub const SEGMENT_HEADER_SIZE: usize = 8;
pub(crate) const MAX_LEN_FIELD: usize = 5;
#[derive(Debug)]
pub struct ChunkSlice<'a> {
pub encoding: u8,
pub data: &'a [u8],
pub segment: u32,
pub offset: u32,
pub encoded_len: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RecordBounds {
pub encoding: usize,
pub data_start: usize,
pub data_end: usize,
pub crc_end: usize,
pub body_len: u32,
}
pub(crate) fn check_header(seg: &[u8], seq: u64) -> Result<()> {
if seg.len() < SEGMENT_HEADER_SIZE {
return Err(Error::format(format!(
"chunk segment {seq} too small: {} bytes",
seg.len()
)));
}
let magic = u32::from_be_bytes([seg[0], seg[1], seg[2], seg[3]]);
if magic != MAGIC_CHUNKS {
return Err(Error::format(format!(
"invalid chunk segment magic 0x{magic:08x} in segment {seq}"
)));
}
if seg[4] != 1 {
return Err(Error::Unsupported(format!(
"chunk segment format version {}",
seg[4]
)));
}
Ok(())
}
pub(crate) fn record_bounds(seg: &[u8], offset: u32) -> Result<RecordBounds> {
let start = offset as usize;
if start < SEGMENT_HEADER_SIZE {
return Err(Error::format(format!(
"chunk offset {start} points into the segment header"
)));
}
if start + MAX_LEN_FIELD > seg.len() {
return Err(Error::format(format!(
"chunk offset {start} leaves no room for the length field"
)));
}
let mut p = start;
let body_len = varint::uvarint(seg, &mut p)?;
if body_len == 0 {
return Err(Error::format("chunk length is zero"));
}
let body_len = u32::try_from(body_len)
.map_err(|_| Error::format(format!("chunk length {body_len} does not fit in u32")))?;
let data_start = p
.checked_add(1)
.ok_or_else(|| Error::format("chunk length overflow"))?;
let data_end = data_start
.checked_add(body_len as usize)
.ok_or_else(|| Error::format("chunk length overflow"))?;
let crc_end = data_end
.checked_add(4)
.ok_or_else(|| Error::format("chunk length overflow"))?;
if crc_end > seg.len() {
return Err(Error::format(format!(
"chunk at offset {start} is truncated: needs {crc_end} bytes, segment has {}",
seg.len()
)));
}
Ok(RecordBounds {
encoding: p,
data_start,
data_end,
crc_end,
body_len,
})
}