Skip to main content

git_pack_delta/
encode.rs

1//! <https://github.com/git/git/blob/master/diff-delta.c>
2
3use crate::{COPY_CMD_FLAG, ZERO_COPY_LEN};
4use crate::{hash::RollingHash, index::DeltaIndex, match_bytes, varint};
5use core::cmp;
6
7/// Maximum length of an insert instruction
8const MAX_INSERT_LEN: usize = 127;
9/// Maximum length of a copy instruction
10const MAX_COPY_LEN: u32 = (1 << (3 * 8)) - 1; // 64 KiB -1
11
12/// A writer for delta instructions
13pub trait DeltaWriter {
14    /// Emits a length prefix for either the base or target.
15    fn emit_len(&mut self, value: usize, base: bool);
16    /// Emits a literal insert instruction with the given data.
17    fn emit_literal(&mut self, data: &[u8]);
18    /// Emits a copy instruction with the given offset and length.
19    fn emit_copy(&mut self, offset: u32, length: u32);
20    /// Returns the total length of the emitted delta instructions.
21    fn len(&self) -> usize;
22    fn is_empty(&self) -> bool {
23        self.len() == 0
24    }
25}
26
27/// Returns the length of the delta encoding for the given base and target using the specified index.
28///
29/// If the length of the delta would exceed `max_output_len`, returns [`None`] instead.
30/// This is ~10-20% faster than actually writing the delta and requires no memory allocations.
31pub fn get_delta_len<H: RollingHash>(
32    base: &[u8],
33    index: &DeltaIndex<H>,
34    target: &[u8],
35    max_output_len: usize,
36) -> Option<usize> {
37    let mut writer = LengthWriter::default();
38    write_delta_to(base, index, target, max_output_len, &mut writer)?;
39    Some(writer.0)
40}
41
42/// Writes delta encoding that can re-create `target` from `base` into a [`DeltaWriter`] (e.g., [`Vec<u8>`]).
43///
44/// Requires a reusable `index` over the `base`.
45/// Returns [`None`] if the output would be larger than `max_output_len`.
46/// Assumes that `writer` is empty.
47pub fn write_delta_to<H: RollingHash>(
48    base: &[u8],
49    index: &DeltaIndex<H>,
50    target: &[u8],
51    max_output_len: usize,
52    writer: &mut impl DeltaWriter,
53) -> Option<()> {
54    let base_len = base.len();
55    let target_len = target.len();
56    if target_len == 0 {
57        return None;
58    }
59    debug_assert_eq!(writer.len(), 0);
60
61    writer.emit_len(base_len, true);
62    writer.emit_len(target_len, false);
63
64    let initial_size = cmp::min(H::WINDOW, target_len);
65    let initial_data = &target[..initial_size];
66    // initialize the rolling hash:
67    let mut hasher = H::from_slice(initial_data);
68    let mut insert_count = initial_size; // size of pending insert command
69    let mut target_pos = initial_size; // ptr in target
70    let mut match_off: u32 = 0; // offset of current match
71    let mut match_len: u32 = 0; // length of current match
72
73    const GOOD_MATCH_LENGTH: u32 = 4096; // good enough
74
75    while target_pos < target_len {
76        debug_assert!(target_pos >= H::WINDOW);
77        if match_len < GOOD_MATCH_LENGTH {
78            // update rolling hash
79            H::roll_once(
80                &mut hasher,
81                target[target_pos],
82                target[target_pos - H::WINDOW],
83            );
84            // find match
85            for ref_start in index.iter_offsets(hasher.value()) {
86                let new_len =
87                    match_bytes::count_matches(&base[ref_start as usize..], &target[target_pos..])
88                        as u32;
89                if new_len > match_len {
90                    // found a better match
91                    match_off = ref_start;
92                    match_len = new_len;
93                    if match_len >= GOOD_MATCH_LENGTH {
94                        break; // good enough
95                    }
96                }
97            }
98        }
99
100        if match_len < 4 {
101            // bad match => use insert command instead
102            insert_count += 1;
103            target_pos += 1;
104            debug_assert!(insert_count <= MAX_INSERT_LEN);
105            if insert_count == MAX_INSERT_LEN {
106                // flush insert command when it reaches max length
107                writer.emit_literal(&target[target_pos - insert_count..target_pos]);
108                insert_count = 0;
109            }
110            match_len = 0; // reset match size for next iteration
111        } else {
112            // good match
113            // try to back-extend the match to include the pending insert bytes
114            let extend = match_bytes::count_matches_rev(
115                &base[..match_off as usize],
116                &target[..target_pos],
117                insert_count,
118            );
119            // dbg!(extend);
120
121            if extend > 0 {
122                match_off -= extend as u32;
123                match_len += extend as u32;
124                insert_count -= extend;
125                target_pos -= extend;
126
127                if insert_count > 0 {
128                    // flush remaining insert command
129                    writer.emit_literal(&target[target_pos - insert_count..target_pos]);
130                    insert_count = 0;
131                }
132            }
133
134            // git still uses the v2 format where copy instructions are limited to 64KiB (ZERO_COPY_LEN).
135            // but we use v3, so a copy can be up to 16MiB (MAX_COPY_LEN)
136            let copy_length = cmp::min(match_len, MAX_COPY_LEN);
137
138            writer.emit_copy(match_off, copy_length);
139            target_pos += copy_length as usize;
140            match_off = match_off.saturating_add(copy_length);
141            match_len -= copy_length;
142            if match_off == u32::MAX {
143                match_len = 0;
144            }
145            if match_len < GOOD_MATCH_LENGTH {
146                // re-seed hash
147                debug_assert!(target_pos >= H::WINDOW);
148                let window = &target[target_pos - H::WINDOW..target_pos];
149                hasher.reset_with(window);
150            }
151        }
152
153        if writer.len() > max_output_len {
154            return None;
155        }
156    }
157
158    debug_assert!(insert_count <= MAX_INSERT_LEN);
159    if insert_count > 0 {
160        // flush remaining insert instruction
161        if writer.len() + insert_count + 1 > max_output_len {
162            return None;
163        }
164        writer.emit_literal(&target[target_len - insert_count..target_len]);
165    } else {
166        if writer.len() > max_output_len {
167            return None;
168        }
169    }
170
171    debug_assert!(writer.len() <= max_output_len);
172    Some(())
173}
174
175impl DeltaWriter for Vec<u8> {
176    #[inline]
177    fn emit_literal(&mut self, data: &[u8]) {
178        let len = data.len();
179        assert!(len > 0);
180        assert!(len <= MAX_INSERT_LEN);
181        self.push(len as u8);
182        self.extend_from_slice(data);
183    }
184    fn emit_copy(&mut self, offset: u32, length: u32) {
185        debug_assert!(length > 0);
186        debug_assert!(length <= MAX_COPY_LEN);
187        let mut value = [0u8; 8];
188        value[0] = COPY_CMD_FLAG; // copy flag
189        let mut i = 1;
190
191        // the compiler will unroll these loops and skip the bounds checks :)
192        for o in 0..4 {
193            if offset & (0xff << (o * 8)) != 0 {
194                value[i] = (offset >> (o * 8)) as u8;
195                i += 1;
196                value[0] |= 1 << o;
197            }
198        }
199
200        // using 3 bits for the length is only supported in v3 of git's delta format.
201        // but git has only been using v2 since 2006. (it can read the newer format, though)
202        if length != ZERO_COPY_LEN {
203            for l in 0..3 {
204                if length & (0xff << (l * 8)) != 0 {
205                    value[i] = (length >> (l * 8)) as u8;
206                    i += 1;
207                    value[0] |= 0x10 << l;
208                }
209            }
210        }
211
212        debug_assert!(i <= 1 + 4 + 3);
213        debug_assert!(i > 0);
214
215        self.extend_from_slice(&value[..i]);
216    }
217    #[inline]
218    fn len(&self) -> usize {
219        self.len()
220    }
221    #[inline]
222    fn emit_len(&mut self, value: usize, _base: bool) {
223        varint::encode_varint(value as u64, self);
224    }
225}
226
227#[derive(Debug, Default)]
228struct LengthWriter(usize);
229
230impl DeltaWriter for LengthWriter {
231    fn emit_len(&mut self, value: usize, _base: bool) {
232        self.0 += varint::get_varint_len(value as u64) as usize;
233    }
234    #[inline]
235    fn emit_literal(&mut self, data: &[u8]) {
236        self.0 += data.len() + 1;
237    }
238    fn emit_copy(&mut self, offset: u32, length: u32) {
239        debug_assert!(length > 0);
240        debug_assert!(length <= MAX_COPY_LEN);
241        let mut i = 1;
242
243        // the compiler will unroll these loops and skip the bounds checks :)
244        for o in 0..4 {
245            if offset & (0xff << (o * 8)) != 0 {
246                i += 1;
247            }
248        }
249
250        // using 3 bits for the length is only supported in v3 of git's delta format.
251        // but git has only been using v2 since 2006. (it can read the newer format, though)
252        if length != ZERO_COPY_LEN {
253            for l in 0..3 {
254                if length & (0xff << (l * 8)) != 0 {
255                    i += 1;
256                }
257            }
258        }
259        debug_assert!(i <= 1 + 4 + 3);
260        debug_assert!(i > 0);
261        self.0 += i;
262    }
263    #[inline]
264    fn len(&self) -> usize {
265        self.0
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn test_emit_copy_instruction() {
275        let data: Vec<(u32, u32, &[u8])> = vec![
276            (0, ZERO_COPY_LEN, &[0b1000_0000]),
277            (
278                0x78563412,
279                ZERO_COPY_LEN,
280                &[0b1000_1111, 0x12, 0x34, 0x56, 0x78],
281            ),
282            (0x78003400, ZERO_COPY_LEN, &[0b1000_1010, 0x34, 0x78]),
283            (0, 0xAB, &[0b1001_0000, 0xAB]),
284            (0, 0xabcdef, &[0b1111_0000, 0xef, 0xcd, 0xab]),
285            (
286                0x78563412,
287                0xabcdef,
288                &[0b1111_1111, 0x12, 0x34, 0x56, 0x78, 0xef, 0xcd, 0xab],
289            ),
290            (0, MAX_COPY_LEN, &[0b1111_0000, 0xff, 0xff, 0xff]),
291        ];
292        for (offset, length, expected) in data {
293            let mut out = Vec::new();
294            out.emit_copy(offset, length);
295            assert_eq!(out, expected);
296        }
297    }
298}