gix_index/extension/end_of_index_entry/
decode.rs

1use crate::{
2    decode::header,
3    extension,
4    extension::end_of_index_entry::{MIN_SIZE, MIN_SIZE_WITH_HEADER, SIGNATURE},
5    util::from_be_u32,
6};
7
8/// Decode the end of index entry extension, which is no more than a glorified offset to the first byte of all extensions to allow
9/// loading entries and extensions in parallel.
10///
11/// Itself it's located at the end of the index file, which allows its location to be known and thus addressable.
12/// From there it's possible to traverse the chunks of all set extensions, hash them, and compare that hash with all extensions
13/// stored prior to this one to assure they are correct.
14///
15/// If the checksum wasn't matched, we will ignore this extension entirely.
16pub fn decode(data: &[u8], object_hash: gix_hash::Kind) -> Result<Option<usize>, gix_hash::hasher::Error> {
17    let hash_len = object_hash.len_in_bytes();
18    if data.len() < MIN_SIZE_WITH_HEADER + hash_len {
19        return Ok(None);
20    }
21
22    let start_of_eoie = data.len() - MIN_SIZE_WITH_HEADER - hash_len;
23    let ext_data = &data[start_of_eoie..data.len() - hash_len];
24
25    let (signature, ext_size, ext_data) = extension::decode::header(ext_data);
26    if signature != SIGNATURE || ext_size as usize != MIN_SIZE {
27        return Ok(None);
28    }
29
30    let (offset, checksum) = ext_data.split_at(4);
31    let Ok(checksum) = gix_hash::oid::try_from_bytes(checksum) else {
32        return Ok(None);
33    };
34    let offset = from_be_u32(offset) as usize;
35    if offset < header::SIZE || offset > start_of_eoie || checksum.kind() != object_hash {
36        return Ok(None);
37    }
38
39    let mut hasher = gix_hash::hasher(object_hash);
40    let mut last_chunk = None;
41    for (signature, chunk) in extension::Iter::new(&data[offset..data.len() - MIN_SIZE_WITH_HEADER - hash_len]) {
42        hasher.update(&signature);
43        hasher.update(&(chunk.len() as u32).to_be_bytes());
44        last_chunk = Some(chunk);
45    }
46
47    if hasher.try_finalize()?.verify(checksum).is_err() {
48        return Ok(None);
49    }
50    // The last-to-this chunk ends where ours starts
51    if last_chunk.is_none_or(|s| !std::ptr::eq(s.as_ptr_range().end, &data[start_of_eoie])) {
52        return Ok(None);
53    }
54
55    Ok(Some(offset))
56}