use crate::error::IndexError;
pub(crate) const MAGIC: [u8; 6] = *b"DSIDX1";
pub(crate) const VERSION: u32 = 1;
pub(crate) struct Reader<'a> {
buf: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
pub(crate) fn new(buf: &'a [u8]) -> Self {
Self { buf, pos: 0 }
}
pub(crate) fn pos(&self) -> usize {
self.pos
}
pub(crate) fn skip(&mut self, n: usize) -> Result<(), IndexError> {
let end = self
.pos
.checked_add(n)
.ok_or(IndexError::Truncated { section: "header" })?;
if end > self.buf.len() {
return Err(IndexError::Truncated { section: "header" });
}
self.pos = end;
Ok(())
}
pub(crate) fn rest(&self) -> &'a [u8] {
self.buf.get(self.pos..).unwrap_or(&[])
}
pub(crate) fn u64(&mut self) -> Result<u64, IndexError> {
let bytes = self.take(8).ok_or(IndexError::Truncated {
section: "u64 field",
})?;
let mut raw = [0u8; 8];
raw.copy_from_slice(bytes);
Ok(u64::from_le_bytes(raw))
}
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let bytes = self.buf.get(self.pos..end)?;
self.pos = end;
Some(bytes)
}
}
pub(crate) fn push_u64(out: &mut Vec<u8>, v: u64) {
out.extend_from_slice(&v.to_le_bytes());
}
pub(crate) fn push_u32(out: &mut Vec<u8>, v: u32) {
out.extend_from_slice(&v.to_le_bytes());
}
pub(crate) fn check_header(bytes: &[u8]) -> Result<(), IndexError> {
let magic = bytes
.get(0..6)
.ok_or(IndexError::Truncated { section: "magic" })?;
if magic != MAGIC {
let mut found = [0u8; 6];
for (slot, byte) in found.iter_mut().zip(magic) {
*slot = *byte;
}
return Err(IndexError::InvalidMagic { found });
}
let version = bytes
.get(6..10)
.map(|b| {
let mut raw = [0u8; 4];
raw.copy_from_slice(b);
u32::from_le_bytes(raw)
})
.ok_or(IndexError::Truncated { section: "version" })?;
if version > VERSION {
return Err(IndexError::UnsupportedVersion {
found: version,
supported: VERSION,
});
}
Ok(())
}