use crate::error::{Error, Result};
pub(crate) const TOC_LEN: usize = 6 * 8 + 4;
#[derive(Debug, Clone, Copy, Default)]
pub struct Toc {
pub symbols: u64,
pub series: u64,
pub label_indices: u64,
pub label_indices_table: u64,
pub postings: u64,
pub postings_table: u64,
}
impl Toc {
pub(crate) fn read(buf: &[u8], verify: bool) -> Result<Self> {
if buf.len() < TOC_LEN {
return Err(Error::format("index file too small for a TOC"));
}
let toc_off = buf.len() - TOC_LEN;
let want = be32(buf, toc_off + 48)?;
crate::checksum::verify(verify, want, &buf[toc_off..toc_off + 48], "index toc")?;
Ok(Self {
symbols: be64(buf, toc_off)?,
series: be64(buf, toc_off + 8)?,
label_indices: be64(buf, toc_off + 16)?,
label_indices_table: be64(buf, toc_off + 24)?,
postings: be64(buf, toc_off + 32)?,
postings_table: be64(buf, toc_off + 40)?,
})
}
pub(crate) fn offsets(&self) -> [(&'static str, u64); 6] {
[
("symbols", self.symbols),
("series", self.series),
("label_indices", self.label_indices),
("label_indices_table", self.label_indices_table),
("postings", self.postings),
("postings_table", self.postings_table),
]
}
}
#[inline]
pub(crate) fn be32(buf: &[u8], off: usize) -> Result<u32> {
let b = buf.get(off..off + 4).ok_or(Error::Eof(off))?;
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
#[inline]
pub(crate) fn be64(buf: &[u8], off: usize) -> Result<u64> {
let b = buf.get(off..off + 8).ok_or(Error::Eof(off))?;
Ok(u64::from_be_bytes([
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
]))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_files_are_rejected() {
assert!(Toc::read(&[0u8; 8], false).is_err());
}
#[test]
fn offsets_are_be() {
let mut buf = vec![0u8; TOC_LEN];
buf[..8].copy_from_slice(&7u64.to_be_bytes());
let toc = Toc::read(&buf, false).unwrap();
assert_eq!(toc.symbols, 7);
assert_eq!(toc.series, 0);
}
}