Skip to main content

ostrya_core/
sizes.rs

1//! The packed entries of the `ostree.sizes` commit metadata.
2//!
3//! The commit metadata key `ostree.sizes` holds a value of type `aay`, with
4//! one packed entry for each object. [`SizeEntry`] is one decoded entry.
5//! [`pack_sizes`] writes the array, and [`unpack_entry`] reads one entry.
6
7use crate::checksum::Checksum;
8use crate::error::{Error, Result};
9use crate::objtype::ObjectType;
10use crate::varint;
11
12/// One decoded `ostree.sizes` entry.
13///
14/// # Packed form
15///
16/// ```text
17/// [32 bytes checksum][varuint64 compressed size][varuint64 unpacked size][1 byte objtype]
18/// ```
19///
20/// The two sizes are LEB128 varints ([`varint`]). The last
21/// byte is the numeric value of the [`ObjectType`]. Newer commits write this
22/// byte. [`unpack_entry`] also accepts an entry with no type byte.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct SizeEntry {
25    /// The checksum of the object.
26    pub checksum: Checksum,
27    /// The compressed size on disk, in bytes.
28    pub compressed: u64,
29    /// The uncompressed size, in bytes.
30    pub unpacked: u64,
31    /// The object type, or `None` if the entry has no type byte.
32    ///
33    /// Older commits omit the type byte.
34    pub objtype: Option<ObjectType>,
35}
36
37/// Appends the [packed form](SizeEntry#packed-form) of `entry` to `out`.
38pub fn pack_entry(entry: &SizeEntry, out: &mut Vec<u8>) {
39    out.extend_from_slice(entry.checksum.as_bytes());
40    varint::encode(entry.compressed, out);
41    varint::encode(entry.unpacked, out);
42    if let Some(ty) = entry.objtype {
43        out.push(ty.as_u32() as u8);
44    }
45}
46
47/// Decodes one packed entry from `buf`.
48///
49/// `buf` must hold exactly one entry.
50///
51/// # Errors
52///
53/// - [`Error::InvalidSizeEntry`] with the reason `entry is shorter than a
54///   checksum` if `buf` is shorter than 32 bytes.
55/// - [`Error::InvalidVarint`] if a size is not a valid varint.
56///   [`varint::decode`] lists the reasons.
57/// - [`Error::InvalidObjectType`] if the type byte is not in the range 1 to 9.
58/// - [`Error::InvalidSizeEntry`] with the reason `entry has trailing bytes` if
59///   more than one byte follows the two sizes.
60pub fn unpack_entry(buf: &[u8]) -> Result<SizeEntry> {
61    if buf.len() < 32 {
62        return Err(Error::InvalidSizeEntry("entry is shorter than a checksum"));
63    }
64    let checksum = Checksum::from_ay(&buf[..32])?;
65    let mut pos = 32;
66    let (compressed, n) = varint::decode(&buf[pos..])?;
67    pos += n;
68    let (unpacked, m) = varint::decode(&buf[pos..])?;
69    pos += m;
70    let objtype = match buf.len() - pos {
71        0 => None,
72        1 => Some(ObjectType::from_u32(u32::from(buf[pos]))?),
73        _ => return Err(Error::InvalidSizeEntry("entry has trailing bytes")),
74    };
75    Ok(SizeEntry {
76        checksum,
77        compressed,
78        unpacked,
79        objtype,
80    })
81}
82
83/// Packs a set of entries into the element buffers of the `aay` array.
84///
85/// The array holds the entries sorted by the hex form of the checksum, in
86/// ASCII order. The function sorts by [`Checksum`] value, because the
87/// [order of `Checksum` values](Checksum#order) is the same order.
88pub fn pack_sizes(mut entries: Vec<SizeEntry>) -> Vec<Vec<u8>> {
89    entries.sort_by_key(|a| a.checksum);
90    entries
91        .iter()
92        .map(|e| {
93            // Worst case: 32 checksum + two 10-byte varint u64 + 1 objtype.
94            let mut buf = Vec::with_capacity(56);
95            pack_entry(e, &mut buf);
96            buf
97        })
98        .collect()
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    fn csum(byte: u8) -> Checksum {
106        Checksum::from_bytes([byte; 32])
107    }
108
109    #[test]
110    fn entry_round_trips_with_objtype() {
111        let entry = SizeEntry {
112            checksum: csum(0xab),
113            compressed: 300,
114            unpacked: 16384,
115            objtype: Some(ObjectType::File),
116        };
117        let mut buf = Vec::new();
118        pack_entry(&entry, &mut buf);
119        // 32 checksum + 2 (varint 300) + 3 (varint 16384) + 1 objtype.
120        assert_eq!(buf.len(), 32 + 2 + 3 + 1);
121        assert_eq!(unpack_entry(&buf).unwrap(), entry);
122    }
123
124    #[test]
125    fn tolerates_absent_objtype_byte() {
126        let entry = SizeEntry {
127            checksum: csum(0x01),
128            compressed: 1,
129            unpacked: 2,
130            objtype: None,
131        };
132        let mut buf = Vec::new();
133        pack_entry(&entry, &mut buf);
134        assert_eq!(buf.len(), 32 + 1 + 1);
135        assert_eq!(unpack_entry(&buf).unwrap().objtype, None);
136    }
137
138    #[test]
139    fn rejects_trailing_garbage() {
140        let mut buf = Vec::new();
141        pack_entry(
142            &SizeEntry {
143                checksum: csum(0x02),
144                compressed: 5,
145                unpacked: 6,
146                objtype: Some(ObjectType::File),
147            },
148            &mut buf,
149        );
150        buf.push(0x00);
151        assert!(matches!(
152            unpack_entry(&buf),
153            Err(Error::InvalidSizeEntry("entry has trailing bytes"))
154        ));
155    }
156
157    #[test]
158    fn pack_sizes_sorts_by_checksum() {
159        let entries = vec![
160            SizeEntry {
161                checksum: csum(0xff),
162                compressed: 1,
163                unpacked: 1,
164                objtype: Some(ObjectType::File),
165            },
166            SizeEntry {
167                checksum: csum(0x00),
168                compressed: 1,
169                unpacked: 1,
170                objtype: Some(ObjectType::File),
171            },
172        ];
173        let packed = pack_sizes(entries);
174        // First packed buffer must be the 0x00 checksum entry.
175        assert_eq!(&packed[0][..32], &[0x00u8; 32]);
176        assert_eq!(&packed[1][..32], &[0xffu8; 32]);
177    }
178}