1use crate::error::{Error, Result};
4
5pub(crate) const TOC_LEN: usize = 6 * 8 + 4;
7
8#[derive(Debug, Clone, Copy, Default)]
14pub struct Toc {
15 pub symbols: u64,
17 pub series: u64,
19 pub label_indices: u64,
21 pub label_indices_table: u64,
23 pub postings: u64,
25 pub postings_table: u64,
27}
28
29impl Toc {
30 pub(crate) fn read(buf: &[u8], verify: bool) -> Result<Self> {
35 if buf.len() < TOC_LEN {
36 return Err(Error::format("index file too small for a TOC"));
37 }
38 let toc_off = buf.len() - TOC_LEN;
39 let want = be32(buf, toc_off + 48)?;
40 crate::checksum::verify(verify, want, &buf[toc_off..toc_off + 48], "index toc")?;
41 Ok(Self {
42 symbols: be64(buf, toc_off)?,
43 series: be64(buf, toc_off + 8)?,
44 label_indices: be64(buf, toc_off + 16)?,
45 label_indices_table: be64(buf, toc_off + 24)?,
46 postings: be64(buf, toc_off + 32)?,
47 postings_table: be64(buf, toc_off + 40)?,
48 })
49 }
50
51 pub(crate) fn offsets(&self) -> [(&'static str, u64); 6] {
55 [
56 ("symbols", self.symbols),
57 ("series", self.series),
58 ("label_indices", self.label_indices),
59 ("label_indices_table", self.label_indices_table),
60 ("postings", self.postings),
61 ("postings_table", self.postings_table),
62 ]
63 }
64}
65
66#[inline]
67pub(crate) fn be32(buf: &[u8], off: usize) -> Result<u32> {
68 let b = buf.get(off..off + 4).ok_or(Error::Eof(off))?;
69 Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
70}
71
72#[inline]
73pub(crate) fn be64(buf: &[u8], off: usize) -> Result<u64> {
74 let b = buf.get(off..off + 8).ok_or(Error::Eof(off))?;
75 Ok(u64::from_be_bytes([
76 b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
77 ]))
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn short_files_are_rejected() {
86 assert!(Toc::read(&[0u8; 8], false).is_err());
87 }
88
89 #[test]
90 fn offsets_are_be() {
91 let mut buf = vec![0u8; TOC_LEN];
92 buf[..8].copy_from_slice(&7u64.to_be_bytes());
93 let toc = Toc::read(&buf, false).unwrap();
94 assert_eq!(toc.symbols, 7);
95 assert_eq!(toc.series, 0);
96 }
97}