Skip to main content

oxabl_cache_format/
pack_footer.rs

1//! `OXPK` pack footer: the segment index.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::ids::SegmentId;
6use crate::limits::PACK_SEGMENTS;
7use crate::pack_header::PACK_HEADER_LEN;
8use crate::pack_trailer::PackTrailer;
9use crate::segment::MIN_SEGMENT_LEN;
10use crate::writer::{Writer, len32};
11
12/// Length of one footer entry.
13pub const FOOTER_ENTRY_LEN: usize = 32 + 8 + 4;
14
15/// Where one segment sits in the pack object. Offsets are absolute.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct PackSegment {
18    pub segment_id: SegmentId,
19    pub offset: u64,
20    pub length: u32,
21}
22
23/// The footer of a pack object. Segments are contiguous from the end of the header.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct PackFooter {
26    pub segments: Vec<PackSegment>,
27}
28
29impl PackFooter {
30    /// Offset the footer starts at: the end of the last segment.
31    pub fn footer_offset(&self) -> Result<u64> {
32        check_layout(&self.segments)
33    }
34
35    /// The trailer for this footer. `hash` is BLAKE3.
36    pub fn trailer(&self, hash: impl FnOnce(&[u8]) -> [u8; 32]) -> Result<PackTrailer> {
37        let footer_offset = self.footer_offset()?;
38        let bytes = self.encode()?;
39        let trailer = PackTrailer {
40            segment_count: len32(self.segments.len(), "segments")?,
41            footer_offset,
42            footer_digest: hash(&bytes),
43        };
44        trailer.check()?;
45        Ok(trailer)
46    }
47
48    pub fn encode(&self) -> Result<Vec<u8>> {
49        check_layout(&self.segments)?;
50        let mut w = Writer::with_capacity(self.segments.len() * FOOTER_ENTRY_LEN);
51        for s in &self.segments {
52            w.bytes(&s.segment_id.0);
53            w.u64(s.offset);
54            w.u32(s.length);
55        }
56        Ok(w.into_vec())
57    }
58
59    /// Decodes the footer bytes that `trailer` describes. `hash` is BLAKE3; the footer is
60    /// rejected unless it hashes to the trailer's digest.
61    pub fn decode(
62        bytes: &[u8],
63        trailer: &PackTrailer,
64        hash: impl FnOnce(&[u8]) -> [u8; 32],
65    ) -> Result<Self> {
66        trailer.check()?;
67        let count = trailer.segment_count as usize;
68        if bytes.len() != count * FOOTER_ENTRY_LEN {
69            return Err(FormatError::Invalid("footer length"));
70        }
71        if hash(bytes) != trailer.footer_digest {
72            return Err(FormatError::Invalid("footer digest"));
73        }
74        let mut c = Cursor::new(bytes);
75        let mut segments = Vec::with_capacity(count);
76        for _ in 0..count {
77            segments.push(PackSegment {
78                segment_id: SegmentId(c.array()?),
79                offset: c.u64()?,
80                length: c.u32()?,
81            });
82        }
83        c.finish()?;
84        if check_layout(&segments)? != trailer.footer_offset {
85            return Err(FormatError::Invalid("footer offset"));
86        }
87        Ok(Self { segments })
88    }
89}
90
91fn check_layout(segments: &[PackSegment]) -> Result<u64> {
92    if segments.len() > PACK_SEGMENTS {
93        return Err(FormatError::LimitExceeded("segments"));
94    }
95    let mut next = PACK_HEADER_LEN as u64;
96    for s in segments {
97        if s.offset != next || (s.length as usize) < MIN_SEGMENT_LEN {
98            return Err(FormatError::Invalid("segment layout"));
99        }
100        next = next
101            .checked_add(u64::from(s.length))
102            .ok_or(FormatError::Invalid("segment layout"))?;
103    }
104    Ok(next)
105}