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) -> Option<usize> {
17    let hash_len = object_hash.len_in_bytes();
18    if data.len() < MIN_SIZE_WITH_HEADER + hash_len {
19        return 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 None;
28    }
29
30    let (offset, checksum) = ext_data.split_at(4);
31    let offset = from_be_u32(offset) as usize;
32    if offset < header::SIZE || offset > start_of_eoie || checksum.len() != gix_hash::Kind::Sha1.len_in_bytes() {
33        return None;
34    }
35
36    let mut hasher = gix_features::hash::hasher(gix_hash::Kind::Sha1);
37    let mut last_chunk = None;
38    for (signature, chunk) in extension::Iter::new(&data[offset..data.len() - MIN_SIZE_WITH_HEADER - hash_len]) {
39        hasher.update(&signature);
40        hasher.update(&(chunk.len() as u32).to_be_bytes());
41        last_chunk = Some(chunk);
42    }
43
44    if hasher.digest() != checksum {
45        return None;
46    }
47    // The last-to-this chunk ends where ours starts
48    if last_chunk.map_or(true, |s| s.as_ptr_range().end != (&data[start_of_eoie]) as *const _) {
49        return None;
50    }
51
52    Some(offset)
53}