1use crate::hash::RollingHash;
4use core::cmp;
5
6const HASH_LIMIT: usize = 64;
8
9#[derive(Debug)]
11pub(crate) struct IndexEntry<H: RollingHash> {
12 pub(crate) offset: u32,
14 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 entries: Vec<IndexEntry<H>>,
29 fan_out: Vec<u32>,
30 hash_mask: u32,
31}
32
33impl<H: RollingHash> DeltaIndex<H> {
34 pub(crate) fn iter_offsets(&self, hash: H::H) -> impl Iterator<Item = u32> {
36 let h_idx = H::apply_mask(hash, self.hash_mask);
37 let lo = self.fan_out[h_idx] as usize;
38 let hi = self.fan_out[h_idx + 1] as usize;
39 debug_assert!(lo <= hi);
40 self.entries[lo..hi]
41 .iter()
42 .filter(move |i| i.hash == hash)
43 .map(|i| i.offset)
44 }
45}
46
47#[derive(Debug)]
48struct UnpackedEntry<H: RollingHash> {
49 entry: IndexEntry<H>,
50 next: Option<u32>,
51}
52
53#[derive(Debug)]
54struct IndexBuilder<H: RollingHash> {
55 h_size: usize,
56 list: Vec<UnpackedEntry<H>>,
58 starts: Vec<Option<u32>>,
60 counts: Vec<u32>,
62}
63
64impl<H: RollingHash> IndexBuilder<H> {
66 fn new(size: usize, h_size: usize) -> Self {
67 Self {
68 h_size,
69 list: Vec::with_capacity(size),
70 starts: vec![None; h_size],
71 counts: vec![0; h_size + 1],
72 }
73 }
74
75 fn push(&mut self, h_index: usize, entry: IndexEntry<H>) {
76 let last_idx = self.starts[h_index];
77 if let Some(idx) = last_idx {
78 debug_assert_eq!(
79 H::apply_mask(self.list[idx as usize].entry.hash, (self.h_size - 1) as u32),
80 h_index
81 );
82 }
83 self.starts[h_index] = Some(self.list.len() as u32);
84 self.list.push(UnpackedEntry {
85 entry,
86 next: last_idx,
87 });
88 self.counts[h_index] += 1;
89 }
90
91 fn cull(&mut self) {
97 for i in 0..self.h_size {
98 if self.counts[i] <= HASH_LIMIT as u32 {
99 continue;
100 }
101
102 let mut acc: i32 = 0;
103 let mut entry = self.starts[i];
104
105 while entry.is_some() {
113 acc += self.counts[i] as i32 - HASH_LIMIT as i32;
114 if acc > 0 {
115 let keep = entry.unwrap();
116 while acc > 0 {
117 entry = self.list[entry.unwrap() as usize].next;
118 acc -= HASH_LIMIT as i32;
119 }
120 self.list[keep as usize].next = entry;
121 }
122 entry = self.list[entry.unwrap() as usize].next;
123 }
124 debug_assert_eq!(acc, 0);
125 }
126 }
127
128 fn build(mut self) -> DeltaIndex<H> {
129 self.cull();
130
131 debug_assert_eq!(self.h_size + 1, self.counts.len());
132 debug_assert_eq!(self.h_size, self.starts.len());
133
134 let h_size = self.h_size;
135 let mut fan_out = self.counts; fan_out.fill(0);
137
138 let mut packed_hashes = Vec::with_capacity(self.list.len());
139 for i in 0..h_size {
140 fan_out[i] = packed_hashes.len() as u32;
142 let mut next_idx = self.starts[i];
143 while let Some(idx) = next_idx {
144 let e = &self.list[idx as usize];
145 packed_hashes.push(e.entry);
146 next_idx = e.next;
147 }
148 }
149 debug_assert_eq!(packed_hashes.len(), self.list.len());
150 fan_out[h_size] = packed_hashes.len() as u32; DeltaIndex {
153 entries: packed_hashes,
154 fan_out,
155 hash_mask: (h_size - 1) as u32,
156 }
157 }
158}
159
160pub fn create_delta_index_custom<H: RollingHash>(base: &[u8]) -> Option<DeltaIndex<H>> {
161 let base_len = base.len();
162 if base_len == 0 {
163 return None;
164 }
165 const MAX_SIZE: usize = u32::MAX as usize;
167 let entries_count = ((cmp::min(base_len, MAX_SIZE) - 1) / H::WINDOW) as u32;
168 if entries_count == 0 {
169 return None;
170 }
171 let h_size = get_h_size(entries_count) as usize;
172 debug_assert!(h_size.is_power_of_two());
173 let hash_mask = (h_size - 1) as u32;
174
175 let mut builder = IndexBuilder::new(entries_count as usize, h_size);
177
178 let mut prev_hash = H::empty();
179 let stride = H::WINDOW as u32;
180
181 let mut pos: u32 = (entries_count - 1) * H::WINDOW as u32;
183 loop {
184 let window_start = (pos + 1) as usize; let window_end = window_start + H::WINDOW;
186 debug_assert!(window_end <= base_len);
187 let window = &base[window_start..window_end];
188 let offset = pos + H::WINDOW as u32;
189 let hash = H::value_from_slice(window);
190 if hash == prev_hash {
191 if let Some(last) = builder.list.last_mut() {
193 debug_assert_eq!(last.entry.hash, hash);
194 last.entry.offset = offset;
195 }
196 } else {
197 prev_hash = hash;
198 let h_index = H::apply_mask(hash, hash_mask); builder.push(h_index, IndexEntry { offset, hash });
200 }
201 if pos == 0 {
202 break;
203 }
204 pos = pos.saturating_sub(stride);
205 }
206
207 Some(builder.build())
208}
209
210fn get_h_size(entries_count: u32) -> u32 {
212 let m = cmp::max(entries_count / 4, 16);
215 if m.is_power_of_two() {
216 core::hint::cold_path();
217 m
218 } else {
219 m.isolate_highest_one() << 1
220 }
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226 const SAMPLE_DATA: &[u8] = include_bytes!("../tests/data/diff-delta.c");
227
228 #[test]
229 fn new_delta_index_git_rabin() {
230 new_delta_index_inner::<crate::hash::GitRabin>();
231 }
232
233 #[test]
234 fn new_delta_index_cyclic_poly32() {
235 new_delta_index_inner::<crate::hash::CyclicPoly32>();
236 }
237
238 #[test]
239 fn new_delta_index_cyclic_poly64() {
240 new_delta_index_inner::<crate::hash::CyclicPoly64>();
241 }
242
243 fn new_delta_index_inner<H: RollingHash>() {
244 let base = SAMPLE_DATA;
245 let index = create_delta_index_custom::<H>(base).unwrap();
246 assert!((index.hash_mask + 1).is_power_of_two());
247 assert_eq!(index.fan_out.len() - 1, (index.hash_mask + 1) as usize);
248
249 for h_idx in 0..(index.fan_out.len() - 1) {
251 let lo = index.fan_out[h_idx] as usize;
252 let hi = index.fan_out[h_idx + 1] as usize;
253 let entries = &index.entries[lo..hi];
254 assert!(entries.is_sorted_by_key(|i| i.offset))
255 }
256 }
257}
258
259#[cfg(kani)]
260mod proofs {
261 use super::*;
262
263 const MAX_ENTRIES: u32 = (u32::MAX - 1) / 16;
264
265 #[kani::proof]
266 #[kani::unwind(1)]
267 fn check_get_h_size() {
268 let entries_count = kani::any();
269 let h_size = get_h_size(entries_count);
272 assert!(h_size.is_power_of_two());
273 let min = cmp::max(entries_count / 4, 16);
274 assert!(h_size >= min);
275 assert!((h_size / 2) < min);
276 }
277}