Skip to main content

git_pack_delta/
index.rs

1//! <https://github.com/git/git/blob/master/diff-delta.c>
2
3use crate::hash::RollingHash;
4use core::cmp;
5
6/// maximum hash entry list for the same hash bucket
7const HASH_LIMIT: usize = 64;
8
9/// Entry in the rabin hash table
10#[derive(Debug)]
11pub(crate) struct IndexEntry<H: RollingHash> {
12    /// offset into the buffer
13    pub(crate) offset: u32,
14    /// rabin fingerprint of the values starting at `offset`
15    pub(crate) hash: H::H,
16}
17
18impl<H: RollingHash> Copy for IndexEntry<H> {}
19
20impl<H: RollingHash> Clone for IndexEntry<H> {
21    fn clone(&self) -> Self {
22        *self
23    }
24}
25
26#[derive(Debug)]
27pub struct DeltaIndex<H: RollingHash> {
28    pub(crate) entries: Vec<Vec<IndexEntry<H>>>,
29    pub(crate) hash_mask: u32,
30}
31
32// TODO: <https://github.com/git/git/commit/29f049a0c277be72637f74f1f90a89dccd3475bc>
33
34pub fn create_delta_index_custom<H: RollingHash>(base: &[u8]) -> Option<DeltaIndex<H>> {
35    let base_len = base.len();
36    if base_len == 0 {
37        return None;
38    }
39    // Current delta format can't encode offsets into reference buffer with more than 32 bits.
40    const MAX_SIZE: usize = u32::MAX as usize;
41    let entries_count = ((cmp::min(base_len, MAX_SIZE) - 1) / H::WINDOW) as u32;
42    if entries_count == 0 {
43        return None;
44    }
45    let h_size = get_h_size(entries_count);
46    debug_assert!(h_size.is_power_of_two());
47    let hash_mask = h_size - 1;
48
49    let mut entries: Vec<Vec<IndexEntry<H>>> = vec![Vec::new(); h_size as usize];
50    // let hash_count = vec![0; h_size];
51
52    let mut prev_hash = H::empty();
53    let stride = H::WINDOW as u32;
54
55    // iterate backward over the source buffer and fill the hash table with fingerprints
56    // TODO: why backwards???
57    let mut pos: u32 = (entries_count - 1) * H::WINDOW as u32;
58    loop {
59        let window_start = (pos + 1) as usize; // why +1???
60        let window_end = window_start + H::WINDOW;
61        debug_assert!(window_end <= base_len);
62        let window = &base[window_start..window_end];
63        let offset = pos + H::WINDOW as u32;
64        let hash = H::value_from_slice(window);
65        let index = H::apply_mask(hash, hash_mask); // index in the hash table
66        if hash == prev_hash {
67            // keep the lowest of consecutive identical blocks
68            if let Some(last) = entries[index].last_mut() {
69                last.offset = offset;
70            }
71        } else {
72            prev_hash = hash;
73            entries[index].push(IndexEntry { offset, hash });
74        }
75        if pos == 0 {
76            break;
77        }
78        pos = pos.saturating_sub(stride);
79    }
80
81    // cull the hash table
82    for bucket in entries.iter_mut() {
83        cull_bucket(bucket);
84    }
85
86    Some(DeltaIndex { entries, hash_mask })
87}
88
89/// Culls a hash table bucket to ensure it contains at most [`HASH_LIMIT`] entries.
90/// Keeps evenly distributed entries from the original bucket.
91fn cull_bucket<T: Copy>(bucket: &mut Vec<T>) {
92    if bucket.len() <= HASH_LIMIT {
93        return;
94    }
95    let mut keep = Vec::with_capacity(HASH_LIMIT);
96    for i in 0..HASH_LIMIT {
97        let idx = i * bucket.len() / HASH_LIMIT;
98        keep.push(bucket[idx]);
99    }
100    *bucket = keep;
101}
102
103/// Returns the smallest power of two that is >= max(entries_count / 4, 16)
104fn get_h_size(entries_count: u32) -> u32 {
105    // git uses a for loop for this.
106    // this only has one branch.
107    let m = cmp::max(entries_count / 4, 16);
108    if m.is_power_of_two() {
109        core::hint::cold_path();
110        m
111    } else {
112        m.isolate_highest_one() << 1
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119    const SAMPLE_DATA: &[u8] = include_bytes!("../tests/data/diff-delta.c");
120
121    #[test]
122    fn new_delta_index_git_rabin() {
123        new_delta_index_inner::<crate::hash::GitRabin>();
124    }
125
126    #[test]
127    fn new_delta_index_cyclic_poly32() {
128        new_delta_index_inner::<crate::hash::CyclicPoly32>();
129    }
130
131    #[test]
132    fn new_delta_index_cyclic_poly64() {
133        new_delta_index_inner::<crate::hash::CyclicPoly64>();
134    }
135
136    fn new_delta_index_inner<H: RollingHash>() {
137        let base = SAMPLE_DATA;
138        let index = create_delta_index_custom::<H>(base).unwrap();
139        assert!((index.hash_mask + 1).is_power_of_two());
140
141        // check that entries are sorted by offset (descending)
142        for bucket in &index.entries {
143            for i in 1..bucket.len() {
144                assert!(bucket[i - 1].offset >= bucket[i].offset);
145            }
146        }
147    }
148
149    #[test]
150    fn cull_bucket_small() {
151        let mut bucket: Vec<_> = (0..HASH_LIMIT).collect();
152        cull_bucket(&mut bucket);
153        assert!(bucket.len() == HASH_LIMIT);
154    }
155
156    #[test]
157    fn cull_bucket_large() {
158        let factor = 7;
159        let mut bucket: Vec<_> = (0..(HASH_LIMIT * factor)).collect();
160        cull_bucket(&mut bucket);
161        let expected: Vec<_> = (0..HASH_LIMIT).map(|i| i * factor).collect();
162        assert!(bucket.len() == HASH_LIMIT);
163        assert_eq!(bucket, expected);
164    }
165}
166
167#[cfg(kani)]
168mod proofs {
169    use super::*;
170
171    const MAX_ENTRIES: u32 = (u32::MAX - 1) / 16;
172
173    #[kani::proof]
174    #[kani::unwind(1)]
175    fn check_get_h_size() {
176        let entries_count = kani::any();
177        // kani::assume(entries_count > 0);
178        // kani::assume(entries_count <= MAX_ENTRIES);
179        let h_size = get_h_size(entries_count);
180        assert!(h_size.is_power_of_two());
181        let min = cmp::max(entries_count / 4, 16);
182        assert!(h_size >= min);
183        assert!((h_size / 2) < min);
184    }
185}