Skip to main content

gix_pack/index/
access.rs

1use std::{mem::size_of, ops::Range};
2
3use crate::{
4    data,
5    index::{self, EntryIndex, FAN_LEN, PrefixLookupResult},
6};
7
8const N32_SIZE: usize = size_of::<u32>();
9const N64_SIZE: usize = size_of::<u64>();
10const V1_HEADER_SIZE: usize = FAN_LEN * N32_SIZE;
11const V2_HEADER_SIZE: usize = N32_SIZE * 2 + FAN_LEN * N32_SIZE;
12const N32_HIGH_BIT: u32 = 1 << 31;
13
14/// Represents an entry within a pack index file, effectively mapping object [`IDs`][gix_hash::ObjectId] to pack data file locations.
15#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone)]
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
17pub struct Entry {
18    /// The ID of the object
19    pub oid: gix_hash::ObjectId,
20    /// The offset to the object's header in the pack data file
21    pub pack_offset: data::Offset,
22    /// The CRC32 hash over all bytes of the pack data entry.
23    ///
24    /// This can be useful for direct copies of pack data entries from one pack to another with insurance there was no bit rot.
25    /// _Note_: Only available in index version 2 or newer
26    pub crc32: Option<u32>,
27}
28
29/// Iteration and access
30impl<T> index::File<T>
31where
32    T: crate::FileData,
33{
34    fn iter_v1(&self) -> impl Iterator<Item = Entry> + '_ {
35        match self.version {
36            index::Version::V1 => self.data[V1_HEADER_SIZE..]
37                .chunks_exact(N32_SIZE + self.hash_len)
38                .take(self.num_objects as usize)
39                .map(|c| {
40                    let (ofs, oid) = c.split_at(N32_SIZE);
41                    Entry {
42                        oid: gix_hash::ObjectId::from_bytes_or_panic(oid),
43                        pack_offset: u64::from(crate::read_u32(ofs)),
44                        crc32: None,
45                    }
46                }),
47            _ => panic!("Cannot use iter_v1() on index of type {:?}", self.version),
48        }
49    }
50
51    fn iter_v2(&self) -> impl Iterator<Item = Entry> + '_ {
52        let pack64_offset = self.offset_pack_offset64_v2();
53        let oids = self.data[V2_HEADER_SIZE..]
54            .chunks_exact(self.hash_len)
55            .take(self.num_objects as usize);
56        let crcs = self.data[self.offset_crc32_v2()..]
57            .as_chunks::<N32_SIZE>()
58            .0
59            .iter()
60            .take(self.num_objects as usize);
61        let offsets = self.data[self.offset_pack_offset_v2()..]
62            .as_chunks::<N32_SIZE>()
63            .0
64            .iter()
65            .take(self.num_objects as usize);
66        assert_eq!(oids.len(), crcs.len());
67        assert_eq!(crcs.len(), offsets.len());
68        match self.version {
69            index::Version::V2 => izip!(oids, crcs, offsets).map(move |(oid, crc32, ofs32)| Entry {
70                oid: gix_hash::ObjectId::from_bytes_or_panic(oid),
71                pack_offset: self.pack_offset_from_offset_v2(ofs32, pack64_offset),
72                crc32: Some(crate::read_u32(crc32)),
73            }),
74            _ => panic!("Cannot use iter_v2() on index of type {:?}", self.version),
75        }
76    }
77
78    /// Returns the object hash at the given index in our list of (sorted) sha1 hashes.
79    /// The index ranges from 0 to `self.num_objects()`
80    ///
81    /// # Panics
82    ///
83    /// If `index` is out of bounds.
84    pub fn oid_at_index(&self, index: EntryIndex) -> &gix_hash::oid {
85        let index = index as usize;
86        let start = match self.version {
87            index::Version::V2 => V2_HEADER_SIZE + index * self.hash_len,
88            index::Version::V1 => V1_HEADER_SIZE + index * (N32_SIZE + self.hash_len) + N32_SIZE,
89        };
90        gix_hash::oid::from_bytes_unchecked(&self.data[start..][..self.hash_len])
91    }
92
93    /// Returns the offset into our pack data file at which to start reading the object at `index`.
94    ///
95    /// # Panics
96    ///
97    /// If `index` is out of bounds.
98    pub fn pack_offset_at_index(&self, index: EntryIndex) -> data::Offset {
99        let index = index as usize;
100        match self.version {
101            index::Version::V2 => {
102                let start = self.offset_pack_offset_v2() + index * N32_SIZE;
103                self.pack_offset_from_offset_v2(&self.data[start..][..N32_SIZE], self.offset_pack_offset64_v2())
104            }
105            index::Version::V1 => {
106                let start = V1_HEADER_SIZE + index * (N32_SIZE + self.hash_len);
107                u64::from(crate::read_u32(&self.data[start..][..N32_SIZE]))
108            }
109        }
110    }
111
112    /// Returns the CRC32 of the object at the given `index`.
113    ///
114    /// _Note_: These are always present for index version 2 or higher.
115    /// # Panics
116    ///
117    /// If `index` is out of bounds.
118    pub fn crc32_at_index(&self, index: EntryIndex) -> Option<u32> {
119        let index = index as usize;
120        match self.version {
121            index::Version::V2 => {
122                let start = self.offset_crc32_v2() + index * N32_SIZE;
123                Some(crate::read_u32(&self.data[start..start + N32_SIZE]))
124            }
125            index::Version::V1 => None,
126        }
127    }
128
129    /// Returns the `index` of the given hash for use with the [`oid_at_index()`][index::File::oid_at_index()],
130    /// [`pack_offset_at_index()`][index::File::pack_offset_at_index()] or [`crc32_at_index()`][index::File::crc32_at_index()].
131    // NOTE: pretty much the same things as in `multi_index::File::lookup`, change things there
132    //       as well.
133    pub fn lookup(&self, id: impl AsRef<gix_hash::oid>) -> Option<EntryIndex> {
134        lookup(id.as_ref(), &self.fan, &|idx| self.oid_at_index(idx))
135    }
136
137    /// Given a `prefix`, find an object that matches it uniquely within this index and return `Some(Ok(entry_index))`.
138    /// If there is more than one object matching the object `Some(Err(())` is returned.
139    ///
140    /// Finally, if no object matches the index, the return value is `None`.
141    ///
142    /// Pass `candidates` to obtain the set of entry-indices matching `prefix`, with the same return value as
143    /// one would have received if it remained `None`. It will be empty if no object matched the `prefix`.
144    ///
145    // NOTE: pretty much the same things as in `index::File::lookup`, change things there
146    //       as well.
147    pub fn lookup_prefix(
148        &self,
149        prefix: gix_hash::Prefix,
150        candidates: Option<&mut Range<EntryIndex>>,
151    ) -> Option<PrefixLookupResult> {
152        lookup_prefix(
153            prefix,
154            candidates,
155            &self.fan,
156            &|idx| self.oid_at_index(idx),
157            self.num_objects,
158        )
159    }
160
161    /// An iterator over all [`Entries`][Entry] of this index file.
162    pub fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = Entry> + 'a> {
163        match self.version {
164            index::Version::V2 => Box::new(self.iter_v2()),
165            index::Version::V1 => Box::new(self.iter_v1()),
166        }
167    }
168
169    /// Return a vector of ascending offsets into our respective pack data file.
170    ///
171    /// Useful to control an iteration over all pack entries in a cache-friendly way.
172    pub fn sorted_offsets(&self) -> Vec<data::Offset> {
173        let mut ofs: Vec<_> = match self.version {
174            index::Version::V1 => self.iter().map(|e| e.pack_offset).collect(),
175            index::Version::V2 => {
176                let offset32_start = &self.data[self.offset_pack_offset_v2()..];
177                let offsets32 = offset32_start
178                    .as_chunks::<N32_SIZE>()
179                    .0
180                    .iter()
181                    .take(self.num_objects as usize);
182                assert_eq!(self.num_objects as usize, offsets32.len());
183                let pack_offset_64_start = self.offset_pack_offset64_v2();
184                offsets32
185                    .map(|offset| self.pack_offset_from_offset_v2(offset, pack_offset_64_start))
186                    .collect()
187            }
188        };
189        ofs.sort_unstable();
190        ofs
191    }
192
193    #[inline]
194    fn offset_crc32_v2(&self) -> usize {
195        V2_HEADER_SIZE + self.num_objects as usize * self.hash_len
196    }
197
198    #[inline]
199    fn offset_pack_offset_v2(&self) -> usize {
200        self.offset_crc32_v2() + self.num_objects as usize * N32_SIZE
201    }
202
203    #[inline]
204    fn offset_pack_offset64_v2(&self) -> usize {
205        self.offset_pack_offset_v2() + self.num_objects as usize * N32_SIZE
206    }
207
208    #[inline]
209    fn pack_offset_from_offset_v2(&self, offset: &[u8], pack64_offset: usize) -> data::Offset {
210        debug_assert_eq!(self.version, index::Version::V2);
211        let ofs32 = crate::read_u32(offset);
212        if (ofs32 & N32_HIGH_BIT) == N32_HIGH_BIT {
213            let from = pack64_offset + (ofs32 ^ N32_HIGH_BIT) as usize * N64_SIZE;
214            crate::read_u64(&self.data[from..][..N64_SIZE])
215        } else {
216            u64::from(ofs32)
217        }
218    }
219}
220
221pub(crate) fn lookup_prefix<'a>(
222    prefix: gix_hash::Prefix,
223    candidates: Option<&mut Range<EntryIndex>>,
224    fan: &[u32; FAN_LEN],
225    oid_at_index: &dyn Fn(EntryIndex) -> &'a gix_hash::oid,
226    num_objects: u32,
227) -> Option<PrefixLookupResult> {
228    let first_byte = prefix.as_oid().first_byte() as usize;
229    let mut upper_bound = fan[first_byte];
230    let mut lower_bound = if first_byte != 0 { fan[first_byte - 1] } else { 0 };
231
232    // Bisect using indices
233    while lower_bound < upper_bound {
234        let mid = u32::midpoint(lower_bound, upper_bound);
235        let mid_sha = oid_at_index(mid);
236
237        use std::cmp::Ordering::*;
238        match prefix.cmp_oid(mid_sha) {
239            Less => upper_bound = mid,
240            Equal => match candidates {
241                Some(candidates) => {
242                    let first_past_entry = ((0..mid).rev())
243                        .take_while(|prev| prefix.cmp_oid(oid_at_index(*prev)) == Equal)
244                        .last();
245
246                    let last_future_entry = ((mid + 1)..num_objects)
247                        .take_while(|next| prefix.cmp_oid(oid_at_index(*next)) == Equal)
248                        .last();
249
250                    *candidates = match (first_past_entry, last_future_entry) {
251                        (Some(first), Some(last)) => first..last + 1,
252                        (Some(first), None) => first..mid + 1,
253                        (None, Some(last)) => mid..last + 1,
254                        (None, None) => mid..mid + 1,
255                    };
256
257                    return if candidates.len() > 1 {
258                        Some(Err(()))
259                    } else {
260                        Some(Ok(mid))
261                    };
262                }
263                None => {
264                    let next = mid + 1;
265                    if next < num_objects && prefix.cmp_oid(oid_at_index(next)) == Equal {
266                        return Some(Err(()));
267                    }
268                    if mid != 0 && prefix.cmp_oid(oid_at_index(mid - 1)) == Equal {
269                        return Some(Err(()));
270                    }
271                    return Some(Ok(mid));
272                }
273            },
274            Greater => lower_bound = mid + 1,
275        }
276    }
277
278    if let Some(candidates) = candidates {
279        *candidates = 0..0;
280    }
281    None
282}
283
284pub(crate) fn lookup<'a>(
285    id: &gix_hash::oid,
286    fan: &[u32; FAN_LEN],
287    oid_at_index: &dyn Fn(EntryIndex) -> &'a gix_hash::oid,
288) -> Option<EntryIndex> {
289    let first_byte = id.first_byte() as usize;
290    let mut upper_bound = fan[first_byte];
291    let mut lower_bound = if first_byte != 0 { fan[first_byte - 1] } else { 0 };
292
293    while lower_bound < upper_bound {
294        let mid = u32::midpoint(lower_bound, upper_bound);
295        let mid_sha = oid_at_index(mid);
296
297        use std::cmp::Ordering::*;
298        match id.cmp(mid_sha) {
299            Less => upper_bound = mid,
300            Equal => return Some(mid),
301            Greater => lower_bound = mid + 1,
302        }
303    }
304    None
305}