Skip to main content

ostrya_core/
sizes.rs

1//! `ostree.sizes` packed entries.
2//!
3//! The commit-metadata key `ostree.sizes` has value type `aay`: an array of
4//! packed byte buffers, one per object, sorted by ASCII checksum. Each buffer
5//! is:
6//!
7//! ```text
8//! [32 bytes checksum][varuint64 compressed size][varuint64 unpacked size][1 byte objtype]
9//! ```
10//!
11//! The trailing objtype byte is present on newer commits; a parser tolerates
12//! its absence.
13
14use crate::checksum::Checksum;
15use crate::error::{Error, Result};
16use crate::objtype::ObjectType;
17use crate::varint;
18
19/// One decoded `ostree.sizes` entry.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct SizeEntry {
22    /// The object identity.
23    pub checksum: Checksum,
24    /// On-disk (compressed) size in bytes.
25    pub compressed: u64,
26    /// Uncompressed size in bytes.
27    pub unpacked: u64,
28    /// Object type, absent on older commits that omit the trailing byte.
29    pub objtype: Option<ObjectType>,
30}
31
32/// Append the packed form of one entry to `out`.
33pub fn pack_entry(entry: &SizeEntry, out: &mut Vec<u8>) {
34    out.extend_from_slice(entry.checksum.as_bytes());
35    varint::encode(entry.compressed, out);
36    varint::encode(entry.unpacked, out);
37    if let Some(ty) = entry.objtype {
38        out.push(ty.as_u32() as u8);
39    }
40}
41
42/// Decode one packed entry from exactly `buf`.
43pub fn unpack_entry(buf: &[u8]) -> Result<SizeEntry> {
44    if buf.len() < 32 {
45        return Err(Error::InvalidSizeEntry("entry is shorter than a checksum"));
46    }
47    let checksum = Checksum::from_ay(&buf[..32])?;
48    let mut pos = 32;
49    let (compressed, n) = varint::decode(&buf[pos..])?;
50    pos += n;
51    let (unpacked, m) = varint::decode(&buf[pos..])?;
52    pos += m;
53    let objtype = match buf.len() - pos {
54        0 => None,
55        1 => Some(ObjectType::from_u32(u32::from(buf[pos]))?),
56        _ => return Err(Error::InvalidSizeEntry("entry has trailing bytes")),
57    };
58    Ok(SizeEntry {
59        checksum,
60        compressed,
61        unpacked,
62        objtype,
63    })
64}
65
66/// Pack a set of entries into the `aay` element buffers, sorted by ASCII
67/// checksum. Byte-wise `Checksum` ordering equals lexicographic ordering of
68/// the hex form, which is the required entry order.
69pub fn pack_sizes(mut entries: Vec<SizeEntry>) -> Vec<Vec<u8>> {
70    entries.sort_by(|a, b| a.checksum.cmp(&b.checksum));
71    entries
72        .iter()
73        .map(|e| {
74            // Worst case: 32 checksum + two 10-byte varint u64 + 1 objtype.
75            let mut buf = Vec::with_capacity(56);
76            pack_entry(e, &mut buf);
77            buf
78        })
79        .collect()
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    fn csum(byte: u8) -> Checksum {
87        Checksum::from_bytes([byte; 32])
88    }
89
90    #[test]
91    fn entry_round_trips_with_objtype() {
92        let entry = SizeEntry {
93            checksum: csum(0xab),
94            compressed: 300,
95            unpacked: 16384,
96            objtype: Some(ObjectType::File),
97        };
98        let mut buf = Vec::new();
99        pack_entry(&entry, &mut buf);
100        // 32 checksum + 2 (varint 300) + 3 (varint 16384) + 1 objtype.
101        assert_eq!(buf.len(), 32 + 2 + 3 + 1);
102        assert_eq!(unpack_entry(&buf).unwrap(), entry);
103    }
104
105    #[test]
106    fn tolerates_absent_objtype_byte() {
107        let entry = SizeEntry {
108            checksum: csum(0x01),
109            compressed: 1,
110            unpacked: 2,
111            objtype: None,
112        };
113        let mut buf = Vec::new();
114        pack_entry(&entry, &mut buf);
115        assert_eq!(buf.len(), 32 + 1 + 1);
116        assert_eq!(unpack_entry(&buf).unwrap().objtype, None);
117    }
118
119    #[test]
120    fn rejects_trailing_garbage() {
121        let mut buf = Vec::new();
122        pack_entry(
123            &SizeEntry {
124                checksum: csum(0x02),
125                compressed: 5,
126                unpacked: 6,
127                objtype: Some(ObjectType::File),
128            },
129            &mut buf,
130        );
131        buf.push(0x00);
132        assert!(matches!(
133            unpack_entry(&buf),
134            Err(Error::InvalidSizeEntry("entry has trailing bytes"))
135        ));
136    }
137
138    #[test]
139    fn pack_sizes_sorts_by_checksum() {
140        let entries = vec![
141            SizeEntry {
142                checksum: csum(0xff),
143                compressed: 1,
144                unpacked: 1,
145                objtype: Some(ObjectType::File),
146            },
147            SizeEntry {
148                checksum: csum(0x00),
149                compressed: 1,
150                unpacked: 1,
151                objtype: Some(ObjectType::File),
152            },
153        ];
154        let packed = pack_sizes(entries);
155        // First packed buffer must be the 0x00 checksum entry.
156        assert_eq!(&packed[0][..32], &[0x00u8; 32]);
157        assert_eq!(&packed[1][..32], &[0xffu8; 32]);
158    }
159}