grit-lib 0.5.32

Core library for the grit Git implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Rabin-window match catalog and pack delta encoder (Git pack delta format).

use std::sync::Arc;

use crate::delta_encode::{push_copy, write_delta_varint, MIN_COPY, WINDOW};

#[path = "roll_hash_tables.rs"]
mod roll_tables;
use roll_tables::{T, U};

const FINGERPRINT_SHIFT: u32 = 23;
const BUCKET_CAP: usize = 64;
const COPY_GOOD_ENOUGH: usize = 4096;
const MAX_INSERT_RUN: u8 = 0x7f;
const MAX_COPY_SLICE: usize = 0x10000;
/// Targets at least this large are probed before a size-bounded encode (see
/// [`BaseMatchCatalog::shares_windows`]).
const PROBE_TARGETS_FROM: usize = 64 * 1024;
/// Evenly spaced places a target is probed at.
const PROBES: usize = 64;

#[derive(Clone, Copy, Debug)]
struct WindowAnchor {
    fingerprint: u32,
    copy_start: usize,
}

/// Precomputed window fingerprints over a base object for delta encoding.
pub(crate) struct BaseMatchCatalog {
    base: Arc<[u8]>,
    bucket_mask: u32,
    bucket_ranges: Vec<usize>,
    anchors: Vec<WindowAnchor>,
}

impl BaseMatchCatalog {
    fn fingerprint_at(base: &[u8], window_start: usize) -> u32 {
        let mut fp = 0u32;
        for i in 1..=WINDOW {
            fp = ((fp << 8) | u32::from(base[window_start + i]))
                ^ T[(fp >> FINGERPRINT_SHIFT) as usize];
        }
        fp
    }

    fn table_slots(window_count: usize) -> usize {
        let target = (window_count / 4).max(1);
        let mut bits = 4usize;
        while (1usize << bits) < target {
            bits += 1;
        }
        1usize << bits
    }

    fn subsample_bucket(list: &mut Vec<WindowAnchor>, cap: usize) {
        if list.len() <= cap {
            return;
        }
        let step = list.len().div_ceil(cap);
        *list = list.iter().step_by(step).copied().collect();
    }

    #[must_use]
    pub fn build(base: &[u8]) -> Self {
        Self::build_shared(Arc::from(base))
    }

    /// Like [`Self::build`], indexing a buffer the caller already shares instead of copying it.
    #[must_use]
    pub fn build_shared(base: Arc<[u8]>) -> Self {
        if base.len() < WINDOW + 1 {
            return Self {
                base,
                bucket_mask: 0,
                bucket_ranges: vec![0, 0],
                anchors: Vec::new(),
            };
        }

        let window_count = (base.len() - 1) / WINDOW;
        let slots = Self::table_slots(window_count);
        let bucket_mask = (slots - 1) as u32;
        let mut buckets: Vec<Vec<WindowAnchor>> = vec![Vec::new(); slots];

        let mut scan = window_count * WINDOW - WINDOW;
        let mut last_fp = !0u32;
        loop {
            let fp = Self::fingerprint_at(&base, scan);
            let bucket = (fp & bucket_mask) as usize;
            if fp == last_fp {
                if let Some(tail) = buckets[bucket].last_mut() {
                    tail.copy_start = scan + WINDOW;
                }
            } else {
                last_fp = fp;
                buckets[bucket].push(WindowAnchor {
                    fingerprint: fp,
                    copy_start: scan + WINDOW,
                });
            }
            if scan == 0 {
                break;
            }
            scan -= WINDOW;
        }

        for bucket in &mut buckets {
            Self::subsample_bucket(bucket, BUCKET_CAP);
        }

        let mut anchors = Vec::new();
        let mut bucket_ranges = Vec::with_capacity(slots + 1);
        for bucket in buckets {
            bucket_ranges.push(anchors.len());
            anchors.extend_from_slice(&bucket);
        }
        bucket_ranges.push(anchors.len());

        Self {
            base,
            bucket_mask,
            bucket_ranges,
            anchors,
        }
    }

    fn candidates(&self, fingerprint: u32) -> &[WindowAnchor] {
        let idx = (fingerprint & self.bucket_mask) as usize;
        let start = self.bucket_ranges[idx];
        let end = self.bucket_ranges[idx + 1];
        &self.anchors[start..end]
    }

    fn best_copy_span(
        &self,
        target: &[u8],
        at: usize,
        fingerprint: u32,
        at_least: usize,
    ) -> (usize, usize) {
        let base = &self.base;
        let base_len = base.len();
        let target_len = target.len();
        let mut best_base = 0usize;
        let mut best_len = at_least;

        for anchor in self.candidates(fingerprint) {
            if anchor.fingerprint != fingerprint {
                continue;
            }
            let mut base_pos = anchor.copy_start;
            if base_pos >= base_len {
                continue;
            }
            let mut tgt_pos = at;
            let mut remain = base_len - base_pos;
            if remain > target_len - tgt_pos {
                remain = target_len - tgt_pos;
            }
            if remain <= best_len {
                break;
            }
            while remain > 0 && target[tgt_pos] == base[base_pos] {
                base_pos += 1;
                tgt_pos += 1;
                remain -= 1;
            }
            let matched = base_pos - anchor.copy_start;
            if matched > best_len {
                best_len = matched;
                best_base = anchor.copy_start;
                if best_len >= COPY_GOOD_ENOUGH {
                    break;
                }
            }
        }
        (best_base, best_len)
    }

    /// Whether any of [`PROBES`] evenly spaced stretches of `target` holds a window
    /// this catalog indexes.
    ///
    /// Each probe fingerprints [`WINDOW`] consecutive positions, so it lines up with
    /// one indexed base window wherever the stretch was copied from the base. A delta
    /// that fits a size bound copies a large share of the target, so it shows up at
    /// some probe; unrelated content (two compressed or encrypted files, say) shows up
    /// at none, and is rejected without scanning the whole target byte by byte.
    fn shares_windows(&self, target: &[u8]) -> bool {
        let span = 2 * WINDOW;
        if self.anchors.is_empty() {
            return false;
        }
        if target.len() <= span {
            return true;
        }
        let last = target.len() - span - 1;
        (0..PROBES).any(|probe| {
            let at = last * probe / (PROBES - 1);
            (at..at + WINDOW).any(|start| {
                let fp = Self::fingerprint_at(target, start);
                self.candidates(fp).iter().any(|a| a.fingerprint == fp)
            })
        })
    }

    #[must_use]
    pub fn encode(&self, target: &[u8], max_size: usize) -> Option<Vec<u8>> {
        // With a size bound, a target that shares no window with the base cannot
        // come in under it: skip the byte-by-byte scan that would find that out.
        if max_size > 0 && target.len() >= PROBE_TARGETS_FROM && !self.shares_windows(target) {
            return None;
        }
        let mut out = Vec::with_capacity(8192.min(target.len() / 4 + 64));
        write_delta_varint(&mut out, self.base.len());
        write_delta_varint(&mut out, target.len());
        if max_size > 0 && out.len() > max_size {
            return None;
        }
        if target.is_empty() {
            return Some(out);
        }

        let body_start = out.len();
        let mut cursor = 0usize;
        let mut rolling = RollingFingerprint::default();
        let mut pending_copy_len = 0usize;
        let mut pending_copy_base = 0usize;
        let mut open_literals: Option<usize> = None;
        let target_len = target.len();

        let prime = WINDOW.min(target_len);
        if prime > 0 {
            for &b in &target[..prime] {
                push_literal(&mut out, &mut open_literals, b, body_start);
            }
            rolling.absorb_prefix(&target[..prime]);
            cursor = prime;
        }

        while cursor < target_len {
            if pending_copy_len < COPY_GOOD_ENOUGH {
                rolling.slide(target, cursor);
                let (base, len) =
                    self.best_copy_span(target, cursor, rolling.value, pending_copy_len);
                if len > pending_copy_len {
                    pending_copy_base = base;
                    pending_copy_len = len;
                }
            }

            if pending_copy_len < MIN_COPY {
                push_literal(&mut out, &mut open_literals, target[cursor], body_start);
                cursor += 1;
                pending_copy_len = 0;
                if max_size > 0 && out.len() > max_size {
                    return None;
                }
                continue;
            }

            let base = &self.base;
            while pending_copy_base > 0
                && cursor > 0
                && open_literals.is_some()
                && base[pending_copy_base - 1] == target[cursor - 1]
            {
                pending_copy_base -= 1;
                cursor -= 1;
                if !pop_literal(&mut out, &mut open_literals, body_start) {
                    pending_copy_base += 1;
                    cursor += 1;
                    break;
                }
                pending_copy_len += 1;
            }

            if pending_copy_len > target_len - cursor {
                pending_copy_len = target_len - cursor;
            }
            if pending_copy_base + pending_copy_len > base.len() {
                pending_copy_len = base.len().saturating_sub(pending_copy_base);
            }
            if pending_copy_len < MIN_COPY {
                pending_copy_len = 0;
                push_literal(&mut out, &mut open_literals, target[cursor], body_start);
                cursor += 1;
                if max_size > 0 && out.len() > max_size {
                    return None;
                }
                continue;
            }

            open_literals = None;

            let mut remaining = pending_copy_len;
            while remaining > 0 {
                let chunk = remaining.min(MAX_COPY_SLICE);
                push_copy(&mut out, pending_copy_base, chunk).ok()?;
                pending_copy_base += chunk;
                cursor += chunk;
                remaining -= chunk;
                if max_size > 0 && out.len() > max_size {
                    return None;
                }
            }
            pending_copy_len = remaining;

            if pending_copy_len < COPY_GOOD_ENOUGH && cursor >= WINDOW {
                rolling.reset_at(target, cursor);
            }
        }

        if max_size > 0 && out.len() > max_size {
            return None;
        }
        Some(out)
    }
}

#[derive(Default)]
struct RollingFingerprint {
    value: u32,
}

impl RollingFingerprint {
    fn absorb_prefix(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.value =
                ((self.value << 8) | u32::from(b)) ^ T[(self.value >> FINGERPRINT_SHIFT) as usize];
        }
    }

    fn slide(&mut self, target: &[u8], at: usize) {
        self.value ^= U[target[at - WINDOW] as usize];
        self.value = ((self.value << 8) | u32::from(target[at]))
            ^ T[(self.value >> FINGERPRINT_SHIFT) as usize];
    }

    fn reset_at(&mut self, target: &[u8], at: usize) {
        self.value = 0;
        for j in 0..WINDOW {
            self.value = ((self.value << 8) | u32::from(target[at - WINDOW + j]))
                ^ T[(self.value >> FINGERPRINT_SHIFT) as usize];
        }
    }
}

fn push_literal(out: &mut Vec<u8>, open_prefix: &mut Option<usize>, byte: u8, body_start: usize) {
    if open_prefix.is_none() {
        out.push(0);
        *open_prefix = Some(out.len() - 1);
    }
    out.push(byte);
    let Some(prefix) = *open_prefix else {
        return;
    };
    debug_assert!(prefix >= body_start);
    let run_len = out[prefix].saturating_add(1);
    if run_len >= MAX_INSERT_RUN {
        out[prefix] = MAX_INSERT_RUN;
        *open_prefix = None;
    } else {
        out[prefix] = run_len;
    }
}

fn pop_literal(out: &mut Vec<u8>, open_prefix: &mut Option<usize>, body_start: usize) -> bool {
    let prefix = match open_prefix {
        Some(p) => *p,
        None => return false,
    };
    if prefix < body_start || out.len() <= prefix + 1 {
        return false;
    }
    out.pop();
    let run_len = out[prefix].saturating_sub(1);
    if run_len == 0 {
        out.truncate(prefix.max(body_start));
        *open_prefix = None;
    } else {
        out[prefix] = run_len;
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;

    fn noise(len: usize, mut seed: u64) -> Vec<u8> {
        (0..len)
            .map(|_| {
                seed ^= seed << 13;
                seed ^= seed >> 7;
                seed ^= seed << 17;
                seed as u8
            })
            .collect()
    }

    #[test]
    fn unrelated_large_target_is_rejected_without_a_scan() {
        let base = noise(256 * 1024, 1);
        let target = noise(256 * 1024, 2);
        let catalog = BaseMatchCatalog::build(&base);
        assert!(!catalog.shares_windows(&target));
        assert!(catalog.encode(&target, target.len() / 2).is_none());
    }

    #[test]
    fn edited_large_target_still_deltas() {
        let base = noise(256 * 1024, 3);
        // A new version: a stretch replaced in the middle, bytes added at the end.
        let mut target = base.clone();
        target[100_000..110_000].copy_from_slice(&noise(10_000, 4));
        target.extend_from_slice(&noise(5_000, 5));
        let catalog = BaseMatchCatalog::build(&base);
        assert!(catalog.shares_windows(&target));
        let delta = catalog
            .encode(&target, target.len() / 2)
            .expect("an edited copy deltas");
        assert!(delta.len() < 20_000, "delta of {} bytes", delta.len());
        // Unbounded encodes are never probed.
        let unrelated = noise(128 * 1024, 6);
        assert!(catalog.encode(&unrelated, 0).is_some());
    }
}