Skip to main content

oxabl_cache_format/
pack_trailer.rs

1//! `OXPK` pack trailer.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::limits::{PACK_BYTES, PACK_SEGMENTS};
6use crate::pack_footer::FOOTER_ENTRY_LEN;
7use crate::pack_header::PACK_HEADER_LEN;
8use crate::writer::Writer;
9
10const MAGIC: [u8; 4] = *b"OXPF";
11
12/// Length of the trailer, the last bytes of a pack.
13pub const PACK_TRAILER_LEN: usize = 48;
14
15/// The trailer of a pack object: where the footer is and what it must hash to.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct PackTrailer {
18    pub segment_count: u32,
19    pub footer_offset: u64,
20    /// BLAKE3 of the footer.
21    pub footer_digest: [u8; 32],
22}
23
24impl PackTrailer {
25    /// Size of the whole pack object this trailer describes.
26    pub fn object_size(&self) -> Result<u64> {
27        u64::from(self.segment_count)
28            .checked_mul(FOOTER_ENTRY_LEN as u64)
29            .and_then(|footer| footer.checked_add(self.footer_offset))
30            .and_then(|end| end.checked_add(PACK_TRAILER_LEN as u64))
31            .ok_or(FormatError::Invalid("pack size"))
32    }
33
34    pub(crate) fn check(&self) -> Result<()> {
35        if self.segment_count as usize > PACK_SEGMENTS {
36            return Err(FormatError::LimitExceeded("segments"));
37        }
38        if self.footer_offset < PACK_HEADER_LEN as u64 {
39            return Err(FormatError::Invalid("footer offset"));
40        }
41        if self.object_size()? > PACK_BYTES {
42            return Err(FormatError::LimitExceeded("pack size"));
43        }
44        Ok(())
45    }
46
47    pub fn encode(&self) -> Result<[u8; PACK_TRAILER_LEN]> {
48        self.check()?;
49        let mut w = Writer::with_capacity(PACK_TRAILER_LEN);
50        w.u32(self.segment_count);
51        w.u64(self.footer_offset);
52        w.bytes(&self.footer_digest);
53        w.bytes(&MAGIC);
54        let mut out = [0u8; PACK_TRAILER_LEN];
55        out.copy_from_slice(&w.into_vec());
56        Ok(out)
57    }
58
59    /// Decodes the last 48 bytes of a pack of `object_size` bytes and checks they agree
60    /// with that size.
61    pub fn decode(bytes: &[u8], object_size: u64) -> Result<Self> {
62        let mut c = Cursor::new(bytes);
63        let segment_count = c.u32()?;
64        let footer_offset = c.u64()?;
65        let footer_digest = c.array()?;
66        if c.array::<4>()? != MAGIC {
67            return Err(FormatError::BadMagic);
68        }
69        c.finish()?;
70        let trailer = Self {
71            segment_count,
72            footer_offset,
73            footer_digest,
74        };
75        trailer.check()?;
76        if trailer.object_size()? != object_size {
77            return Err(FormatError::Invalid("trailer disagrees with the pack size"));
78        }
79        Ok(trailer)
80    }
81}