1use crate::hash::RollingHash;
4use core::cmp;
5use core::hint::cold_path;
6
7const HASH_LIMIT: usize = 64;
9
10#[derive(Debug)]
12pub(crate) struct IndexEntry<H: RollingHash> {
13 pub(crate) offset: u32,
15 pub(crate) hash: H::H,
17}
18
19impl<H: RollingHash> Copy for IndexEntry<H> {}
20
21impl<H: RollingHash> Clone for IndexEntry<H> {
22 fn clone(&self) -> Self {
23 *self
24 }
25}
26
27#[derive(Debug)]
28pub struct DeltaIndex<H: RollingHash> {
29 entries: Vec<IndexEntry<H>>,
30 fan_out: Vec<u32>,
31 hash_mask: u32,
32}
33
34impl<H: RollingHash> DeltaIndex<H> {
35 pub(crate) fn iter_offsets(&self, hash: H::H) -> impl Iterator<Item = u32> {
37 let h_idx = H::apply_mask(hash, self.hash_mask);
38 let lo = self.fan_out[h_idx] as usize;
39 let hi = self.fan_out[h_idx + 1] as usize;
40 debug_assert!(lo <= hi);
41 self.entries[lo..hi]
42 .iter()
43 .filter(move |i| i.hash == hash)
44 .map(|i| i.offset)
45 }
46}
47
48#[derive(Debug)]
49struct UnpackedEntry<H: RollingHash> {
50 entry: IndexEntry<H>,
51 next: Option<u32>,
52}
53
54#[derive(Debug)]
55struct IndexBuilder<H: RollingHash> {
56 h_size: usize,
57 list: Vec<UnpackedEntry<H>>,
59 starts: Vec<Option<u32>>,
61 counts: Vec<u32>,
63}
64
65impl<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, hash: H::H, offset: u32) {
76 let h_index = H::apply_mask(hash, (self.h_size - 1) as u32);
77 let last_idx = self.starts[h_index];
78 if let Some(idx) = last_idx {
79 debug_assert_eq!(
80 H::apply_mask(self.list[idx as usize].entry.hash, (self.h_size - 1) as u32),
81 h_index
82 );
83 }
84 self.starts[h_index] = Some(self.list.len() as u32);
85 self.list.push(UnpackedEntry {
86 entry: IndexEntry { offset, hash },
87 next: last_idx,
88 });
89 self.counts[h_index] += 1;
90 }
91
92 fn cull(&mut self) {
98 for i in 0..self.h_size {
99 if self.counts[i] <= HASH_LIMIT as u32 {
100 continue;
101 }
102 cold_path();
103
104 let bucket_count = u64::from(self.counts[i]);
105 let keep_count = HASH_LIMIT as u64;
106 let mut acc = bucket_count - keep_count;
107 let mut entry = self.starts[i];
108 let mut last_kept = None;
109 let mut kept_count = 0;
110
111 while let Some(idx) = entry {
112 let next = self.list[idx as usize].next;
113 acc += keep_count;
114 if acc >= bucket_count {
115 acc -= bucket_count;
116 if let Some(last) = last_kept {
117 self.list[last as usize].next = Some(idx);
118 } else {
119 self.starts[i] = Some(idx);
120 }
121 last_kept = Some(idx);
122 kept_count += 1;
123 }
124 entry = next;
125 }
126
127 if let Some(last) = last_kept {
128 self.list[last as usize].next = None;
129 }
130 debug_assert_eq!(kept_count, HASH_LIMIT as u32);
131 self.counts[i] = kept_count;
132 }
133 }
134
135 fn build(mut self) -> DeltaIndex<H> {
136 self.cull();
137
138 debug_assert_eq!(self.h_size + 1, self.counts.len());
139 debug_assert_eq!(self.h_size, self.starts.len());
140
141 let h_size = self.h_size;
142 let expected_entries = self.counts[..h_size]
143 .iter()
144 .map(|&count| count as usize)
145 .sum::<usize>();
146 let mut fan_out = self.counts; fan_out.fill(0);
148
149 let mut packed_hashes = Vec::with_capacity(self.list.len());
150 for i in 0..h_size {
151 fan_out[i] = packed_hashes.len() as u32;
153 let mut next_idx = self.starts[i];
154 while let Some(idx) = next_idx {
155 let e = &self.list[idx as usize];
156 packed_hashes.push(e.entry);
157 next_idx = e.next;
158 }
159 }
160 debug_assert_eq!(packed_hashes.len(), expected_entries);
161 fan_out[h_size] = packed_hashes.len() as u32; DeltaIndex {
164 entries: packed_hashes,
165 fan_out,
166 hash_mask: (h_size - 1) as u32,
167 }
168 }
169}
170
171pub fn create_delta_index_custom<H: RollingHash>(base: &[u8]) -> Option<DeltaIndex<H>> {
175 create_delta_index_custom_stride(base, 16)
176}
177
178pub fn create_delta_index_custom_stride<H: RollingHash>(
189 base: &[u8],
190 stride: u32,
191) -> Option<DeltaIndex<H>> {
192 assert!(stride > 0);
193 let base_len = base.len();
194 if base_len == 0 {
195 return None;
196 }
197 const MAX_SIZE: usize = u32::MAX as usize;
199 let entries_count = ((cmp::min(base_len, MAX_SIZE) - 1) / H::WINDOW) as u32;
200 if entries_count == 0 {
201 return None;
202 }
203 let h_size = get_h_size(entries_count) as usize;
204 debug_assert!(h_size.is_power_of_two());
205
206 let mut builder = IndexBuilder::new(entries_count as usize, h_size);
208
209 let mut prev_hash = H::empty();
210
211 let mut pos: u32 = (entries_count - 1) * H::WINDOW as u32;
213 loop {
214 let window_start = (pos + 1) as usize;
215 let window_end = window_start + H::WINDOW;
216 debug_assert!(window_end <= base_len);
217 let window = &base[window_start..window_end];
218 let offset = pos + H::WINDOW as u32;
219 let hash = H::value_from_slice(window);
220 if hash == prev_hash {
221 let last = builder.list.last_mut().unwrap();
223 debug_assert_eq!(last.entry.hash, hash);
224 last.entry.offset = offset;
225 } else {
226 prev_hash = hash;
227 builder.push(hash, offset);
228 }
229 if pos == 0 {
230 break;
231 }
232 pos = pos.saturating_sub(stride);
233 }
234
235 Some(builder.build())
236}
237
238fn get_h_size(entries_count: u32) -> u32 {
240 let m = cmp::max(entries_count / 4, 16);
243 if m.is_power_of_two() {
244 cold_path();
245 m
246 } else {
247 m.isolate_highest_one() << 1
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254 const SAMPLE_DATA: &[u8] = include_bytes!("../tests/data/diff-delta.c");
255
256 #[test]
257 fn index_builder_packs_entries_by_bucket() {
258 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(4, 4);
259 builder.push(0, 40);
260 builder.push(1, 10);
261 builder.push(5, 20);
262 builder.push(2, 30);
263
264 let index = builder.build();
265
266 assert_eq!(index.fan_out, [0, 1, 3, 4, 4]);
267 assert_eq!(
268 index
269 .entries
270 .iter()
271 .map(|entry| (entry.offset, entry.hash))
272 .collect::<Vec<_>>(),
273 [(40, 0), (20, 5), (10, 1), (30, 2)]
274 );
275 }
276
277 #[test]
278 fn index_builder_culls_overfull_bucket_evenly() {
279 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(128, 16);
280 for offset in 0..128 {
281 builder.push(1, offset);
282 }
283
284 let index = builder.build();
285
286 let expected = (0..HASH_LIMIT)
287 .map(|i| 127 - (i * 2) as u32)
288 .collect::<Vec<_>>();
289 assert_eq!(index.iter_offsets(1).collect::<Vec<_>>(), expected);
290 }
291
292 #[test]
293 fn index_builder_culls_bucket_one_entry_over_limit() {
294 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(HASH_LIMIT + 1, 16);
295 for offset in 0..=HASH_LIMIT as u32 {
296 builder.push(1, offset);
297 }
298
299 let index = builder.build();
300
301 assert_eq!(index.iter_offsets(1).count(), HASH_LIMIT);
302 }
303
304 #[test]
305 fn delta_index_iter_offsets_filters_hashes_in_same_bucket() {
306 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(3, 4);
307 builder.push(1, 10);
308 builder.push(5, 20);
309 builder.push(1, 30);
310
311 let index = builder.build();
312
313 assert_eq!(index.iter_offsets(1).collect::<Vec<_>>(), [30, 10]);
314 assert_eq!(index.iter_offsets(5).collect::<Vec<_>>(), [20]);
315 assert_eq!(index.iter_offsets(9).collect::<Vec<_>>(), []);
316 }
317
318 #[test]
319 fn new_delta_index_git_rabin() {
320 new_delta_index_inner::<crate::hash::GitRabin>();
321 }
322
323 #[test]
324 fn new_delta_index_cyclic_poly32() {
325 new_delta_index_inner::<crate::hash::CyclicPoly32>();
326 }
327
328 #[test]
329 fn new_delta_index_cyclic_poly64() {
330 new_delta_index_inner::<crate::hash::CyclicPoly64>();
331 }
332
333 fn new_delta_index_inner<H: RollingHash>() {
334 let base = SAMPLE_DATA;
335 let index = create_delta_index_custom::<H>(base).unwrap();
336 assert!((index.hash_mask + 1).is_power_of_two());
337 assert_eq!(index.fan_out.len() - 1, (index.hash_mask + 1) as usize);
338
339 for h_idx in 0..(index.fan_out.len() - 1) {
341 let lo = index.fan_out[h_idx] as usize;
342 let hi = index.fan_out[h_idx + 1] as usize;
343 let entries = &index.entries[lo..hi];
344 assert!(entries.is_sorted_by_key(|i| i.offset))
345 }
346 }
347}
348
349#[cfg(kani)]
350mod proofs {
351 use super::*;
352
353 const MAX_ENTRIES: u32 = (u32::MAX - 1) / 16;
354
355 #[kani::proof]
356 #[kani::unwind(1)]
357 fn check_get_h_size() {
358 let entries_count = kani::any();
359 let h_size = get_h_size(entries_count);
362 assert!(h_size.is_power_of_two());
363 let min = cmp::max(entries_count / 4, 16);
364 assert!(h_size >= min);
365 assert!((h_size / 2) < min);
366 }
367}