use bytes::{Buf, BufMut};
use crate::{Error, Result};
pub const BLOCK_SIZE: usize = 4096;
pub const FOOTER_SIZE: usize = 64;
const MAGIC: u32 = 0x4A444258;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Footer {
pub index_offset: u64,
pub index_len: u64,
pub num_blocks: u64,
pub num_entries: u64,
}
impl Footer {
pub const fn new(index_offset: u64, index_len: u64, num_blocks: u64, num_entries: u64) -> Self {
Self {
index_offset,
index_len,
num_blocks,
num_entries,
}
}
pub fn encode(&self, buf: &mut [u8]) {
debug_assert!(buf.len() >= FOOTER_SIZE);
let mut w = &mut buf[..FOOTER_SIZE];
w.put_u64(self.index_offset);
w.put_u64(self.index_len);
w.put_u64(self.num_blocks);
w.put_u64(self.num_entries);
w.put_bytes(0, FOOTER_SIZE - 32 - 4);
w.put_u32(MAGIC);
}
pub fn decode(buf: &[u8]) -> Result<Self> {
if buf.len() < FOOTER_SIZE {
return Err(Error::InvalidFooter);
}
let magic_offset = FOOTER_SIZE - 4;
let magic = u32::from_be_bytes([
buf[magic_offset],
buf[magic_offset + 1],
buf[magic_offset + 2],
buf[magic_offset + 3],
]);
if magic != MAGIC {
return Err(Error::MagicMismatch {
expected: MAGIC,
actual: magic,
});
}
let mut r = buf;
Ok(Self {
index_offset: r.get_u64(),
index_len: r.get_u64(),
num_blocks: r.get_u64(),
num_entries: r.get_u64(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn footer_roundtrip() {
let footer = Footer::new(4096, 512, 10, 1000);
let mut buf = [0u8; FOOTER_SIZE];
footer.encode(&mut buf);
let decoded = Footer::decode(&buf).unwrap();
assert_eq!(footer, decoded);
}
#[test]
fn footer_magic_check() {
let mut buf = [0u8; FOOTER_SIZE];
buf[FOOTER_SIZE - 4..].copy_from_slice(&0xDEADBEEFu32.to_be_bytes());
let err = Footer::decode(&buf).unwrap_err();
assert!(matches!(err, Error::MagicMismatch { .. }));
}
}