Skip to main content

gix_pack/data/entry/
header.rs

1use std::io;
2
3use super::{BLOB, COMMIT, OFS_DELTA, REF_DELTA, TAG, TREE};
4use crate::data;
5
6/// The header portion of a pack data entry, identifying the kind of stored object.
7#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9#[expect(missing_docs)]
10pub enum Header {
11    /// The object is a commit
12    Commit,
13    /// The object is a tree
14    Tree,
15    /// The object is a blob
16    Blob,
17    /// The object is a tag
18    Tag,
19    /// Describes a delta-object which needs to be applied to a base identified by `base_id`.
20    /// The base may occur anywhere in the same pack or in the parent repository, as it does in a **thin-pack**.
21    ///
22    /// **The naming** is exactly the same as the canonical implementation uses, namely **REF_DELTA**.
23    RefDelta { base_id: gix_hash::ObjectId },
24    /// Describes a delta-object present in this pack which acts as base for this object.
25    /// The base object is measured as a distance from this objects
26    /// pack offset, so that `base_pack_offset = this_objects_pack_offset - base_distance`
27    ///
28    /// # Note
29    ///
30    /// **The naming** is exactly the same as the canonical implementation uses, namely **OFS_DELTA**.
31    OfsDelta { base_distance: u64 },
32}
33
34impl Header {
35    /// Subtract `distance` from `pack_offset` safely, returning only offsets beyond the pack header.
36    pub fn verified_base_pack_offset(pack_offset: data::Offset, distance: u64) -> Option<data::Offset> {
37        if distance == 0 {
38            return None;
39        }
40        pack_offset
41            .checked_sub(distance)
42            .filter(|offset| *offset >= data::header::SIZE as data::Offset)
43    }
44    /// Convert the header's object kind into [`gix_object::Kind`] if possible
45    pub fn as_kind(&self) -> Option<gix_object::Kind> {
46        use gix_object::Kind::*;
47        Some(match self {
48            Header::Tree => Tree,
49            Header::Blob => Blob,
50            Header::Commit => Commit,
51            Header::Tag => Tag,
52            Header::RefDelta { .. } | Header::OfsDelta { .. } => return None,
53        })
54    }
55    /// Convert this header's object kind into the packs internal representation
56    pub fn as_type_id(&self) -> u8 {
57        use Header::*;
58        match self {
59            Blob => BLOB,
60            Tree => TREE,
61            Commit => COMMIT,
62            Tag => TAG,
63            OfsDelta { .. } => OFS_DELTA,
64            RefDelta { .. } => REF_DELTA,
65        }
66    }
67    /// Return's true if this is a delta object, i.e. not a full object.
68    pub fn is_delta(&self) -> bool {
69        matches!(self, Header::OfsDelta { .. } | Header::RefDelta { .. })
70    }
71    /// Return's true if this is a base object, i.e. not a delta object.
72    pub fn is_base(&self) -> bool {
73        !self.is_delta()
74    }
75}
76
77impl Header {
78    /// Encode this header along the given `decompressed_size_in_bytes` into the `out` write stream for use within a data pack.
79    ///
80    /// Returns the amount of bytes written to `out`.
81    /// `decompressed_size_in_bytes` is the full size in bytes of the object that this header represents
82    pub fn write_to(&self, decompressed_size_in_bytes: u64, out: &mut dyn io::Write) -> io::Result<usize> {
83        let mut size = decompressed_size_in_bytes;
84        let mut written = 1;
85        let mut c: u8 = (self.as_type_id() << 4) | (size as u8 & 0b0000_1111);
86        size >>= 4;
87        while size != 0 {
88            out.write_all(&[c | 0b1000_0000])?;
89            written += 1;
90            c = size as u8 & 0b0111_1111;
91            size >>= 7;
92        }
93        out.write_all(&[c])?;
94
95        use Header::*;
96        match self {
97            RefDelta { base_id: oid } => {
98                out.write_all(oid.as_slice())?;
99                written += oid.as_slice().len();
100            }
101            OfsDelta { base_distance } => {
102                let mut buf = [0u8; 10];
103                let buf = leb64_encode(*base_distance, &mut buf);
104                out.write_all(buf)?;
105                written += buf.len();
106            }
107            Blob | Tree | Commit | Tag => {}
108        }
109        Ok(written)
110    }
111
112    /// The size of the header in bytes when written in canonical form.
113    ///
114    /// This is the number of bytes [`Self::write_to()`] would emit for `decompressed_size`.
115    /// It does not inspect existing pack bytes and therefore does not preserve non-canonical
116    /// overlong size encodings. Use [`data::Entry::header_size()`] for decoded entries when the
117    /// result has to match the header length present in the pack.
118    pub fn size(&self, decompressed_size: u64) -> usize {
119        self.write_to(decompressed_size, &mut io::sink())
120            .expect("io::sink() to never fail")
121    }
122}
123
124#[inline]
125fn leb64_encode(mut n: u64, buf: &mut [u8; 10]) -> &[u8] {
126    let mut bytes_written = 1;
127    buf[buf.len() - 1] = n as u8 & 0b0111_1111;
128    for out in buf.iter_mut().rev().skip(1) {
129        n >>= 7;
130        if n == 0 {
131            break;
132        }
133        n -= 1;
134        *out = 0b1000_0000 | (n as u8 & 0b0111_1111);
135        bytes_written += 1;
136    }
137    debug_assert_eq!(n, 0, "BUG: buffer must be large enough to hold a 64 bit integer");
138    &buf[buf.len() - bytes_written..]
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn leb64_encode_max_int() {
147        let mut buf = [0u8; 10];
148        let buf = leb64_encode(u64::MAX, &mut buf);
149        assert_eq!(buf.len(), 10, "10 bytes should be used when 64bits are encoded");
150    }
151
152    #[test]
153    fn verified_base_pack_offset_rejects_the_pack_header() {
154        let first_entry_offset = data::header::SIZE as data::Offset;
155        assert_eq!(
156            Header::verified_base_pack_offset(first_entry_offset + 1, 1),
157            Some(first_entry_offset)
158        );
159        for (pack_offset, distance) in [
160            (first_entry_offset + 1, 0),
161            (first_entry_offset, 1),
162            (first_entry_offset, first_entry_offset),
163            (first_entry_offset, first_entry_offset + 1),
164        ] {
165            assert_eq!(
166                Header::verified_base_pack_offset(pack_offset, distance),
167                None,
168                "offset {pack_offset} and distance {distance} cannot point to a pack entry"
169            );
170        }
171    }
172}