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>> {
172 let base_len = base.len();
173 if base_len == 0 {
174 return None;
175 }
176 const MAX_SIZE: usize = u32::MAX as usize;
178 let entries_count = ((cmp::min(base_len, MAX_SIZE) - 1) / H::WINDOW) as u32;
179 if entries_count == 0 {
180 return None;
181 }
182 let h_size = get_h_size(entries_count) as usize;
183 debug_assert!(h_size.is_power_of_two());
184
185 let mut builder = IndexBuilder::new(entries_count as usize, h_size);
187
188 let mut prev_hash = H::empty();
189 let stride = H::WINDOW as u32;
190
191 let mut pos: u32 = (entries_count - 1) * H::WINDOW as u32;
193 loop {
194 let window_start = (pos + 1) as usize;
195 let window_end = window_start + H::WINDOW;
196 debug_assert!(window_end <= base_len);
197 let window = &base[window_start..window_end];
198 let offset = pos + H::WINDOW as u32;
199 let hash = H::value_from_slice(window);
200 if hash == prev_hash {
201 let last = builder.list.last_mut().unwrap();
203 debug_assert_eq!(last.entry.hash, hash);
204 last.entry.offset = offset;
205 } else {
206 prev_hash = hash;
207 builder.push(hash, offset);
208 }
209 if pos == 0 {
210 break;
211 }
212 pos = pos.saturating_sub(stride);
213 }
214
215 Some(builder.build())
216}
217
218fn get_h_size(entries_count: u32) -> u32 {
220 let m = cmp::max(entries_count / 4, 16);
223 if m.is_power_of_two() {
224 cold_path();
225 m
226 } else {
227 m.isolate_highest_one() << 1
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234 const SAMPLE_DATA: &[u8] = include_bytes!("../tests/data/diff-delta.c");
235
236 #[test]
237 fn index_builder_packs_entries_by_bucket() {
238 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(4, 4);
239 builder.push(0, 40);
240 builder.push(1, 10);
241 builder.push(5, 20);
242 builder.push(2, 30);
243
244 let index = builder.build();
245
246 assert_eq!(index.fan_out, [0, 1, 3, 4, 4]);
247 assert_eq!(
248 index
249 .entries
250 .iter()
251 .map(|entry| (entry.offset, entry.hash))
252 .collect::<Vec<_>>(),
253 [(40, 0), (20, 5), (10, 1), (30, 2)]
254 );
255 }
256
257 #[test]
258 fn index_builder_culls_overfull_bucket_evenly() {
259 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(128, 16);
260 for offset in 0..128 {
261 builder.push(1, offset);
262 }
263
264 let index = builder.build();
265
266 let expected = (0..HASH_LIMIT)
267 .map(|i| 127 - (i * 2) as u32)
268 .collect::<Vec<_>>();
269 assert_eq!(index.iter_offsets(1).collect::<Vec<_>>(), expected);
270 }
271
272 #[test]
273 fn index_builder_culls_bucket_one_entry_over_limit() {
274 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(HASH_LIMIT + 1, 16);
275 for offset in 0..=HASH_LIMIT as u32 {
276 builder.push(1, offset);
277 }
278
279 let index = builder.build();
280
281 assert_eq!(index.iter_offsets(1).count(), HASH_LIMIT);
282 }
283
284 #[test]
285 fn delta_index_iter_offsets_filters_hashes_in_same_bucket() {
286 let mut builder = IndexBuilder::<crate::hash::CyclicPoly32>::new(3, 4);
287 builder.push(1, 10);
288 builder.push(5, 20);
289 builder.push(1, 30);
290
291 let index = builder.build();
292
293 assert_eq!(index.iter_offsets(1).collect::<Vec<_>>(), [30, 10]);
294 assert_eq!(index.iter_offsets(5).collect::<Vec<_>>(), [20]);
295 assert_eq!(index.iter_offsets(9).collect::<Vec<_>>(), []);
296 }
297
298 #[test]
299 fn new_delta_index_git_rabin() {
300 new_delta_index_inner::<crate::hash::GitRabin>();
301 }
302
303 #[test]
304 fn new_delta_index_cyclic_poly32() {
305 new_delta_index_inner::<crate::hash::CyclicPoly32>();
306 }
307
308 #[test]
309 fn new_delta_index_cyclic_poly64() {
310 new_delta_index_inner::<crate::hash::CyclicPoly64>();
311 }
312
313 fn new_delta_index_inner<H: RollingHash>() {
314 let base = SAMPLE_DATA;
315 let index = create_delta_index_custom::<H>(base).unwrap();
316 assert!((index.hash_mask + 1).is_power_of_two());
317 assert_eq!(index.fan_out.len() - 1, (index.hash_mask + 1) as usize);
318
319 for h_idx in 0..(index.fan_out.len() - 1) {
321 let lo = index.fan_out[h_idx] as usize;
322 let hi = index.fan_out[h_idx + 1] as usize;
323 let entries = &index.entries[lo..hi];
324 assert!(entries.is_sorted_by_key(|i| i.offset))
325 }
326 }
327}
328
329#[cfg(kani)]
330mod proofs {
331 use super::*;
332
333 const MAX_ENTRIES: u32 = (u32::MAX - 1) / 16;
334
335 #[kani::proof]
336 #[kani::unwind(1)]
337 fn check_get_h_size() {
338 let entries_count = kani::any();
339 let h_size = get_h_size(entries_count);
342 assert!(h_size.is_power_of_two());
343 let min = cmp::max(entries_count / 4, 16);
344 assert!(h_size >= min);
345 assert!((h_size / 2) < min);
346 }
347}