Skip to main content

git_pack_delta/
lib.rs

1//! Creates a delta encoding that can be used to create `target` from `base`.
2//! ```
3//! let base = "This is a pure rust implementation of Git's delta compression algorithm.";
4//! let target = base.replace("Git", "git");
5//! let delta = git_pack_delta::create_delta(base.as_bytes(), target.as_bytes()).unwrap();
6//! assert_eq!(delta.len(), 9);
7//! let target2 = git_pack_delta::patch_delta(base.as_bytes(), &delta).unwrap();
8//! assert_eq!(target.as_bytes(), target2);
9//! ```
10//! See: <https://github.com/git/git/blob/master/diff-delta.c>
11//! and <https://github.com/git/git/blob/master/patch-delta.c>
12
13// TODO: make std optional when Cursor becomes stable in core.
14// #![cfg_attr(not(feature = "std"), no_std)]
15
16#[macro_use]
17extern crate static_assertions_next;
18
19mod decode;
20mod encode;
21pub mod hash;
22mod index;
23pub mod match_bytes;
24pub mod varint;
25
26type DefaultHash = hash::CyclicPoly32;
27
28const COPY_CMD_FLAG: u8 = 0x80;
29const ZERO_COPY_LEN: u32 = 0x10000;
30
31pub use decode::DiffDecodeError;
32pub use encode::DeltaWriter;
33pub use encode::get_delta_len;
34pub use encode::write_delta_to;
35pub use hash::RollingHash;
36pub use index::DeltaIndex;
37pub use index::create_delta_index_custom;
38pub use index::create_delta_index_custom_stride;
39
40/// Writes delta encoding that can re-create `target` from `base` into a [`Vec<u8>`].
41///
42/// Requires a reusable `index` over the `base`.
43/// Returns [`None`] if the output would be larger than `max_output_len`.
44pub fn write_delta_to_vec<H: RollingHash>(
45    base: &[u8],
46    index: &DeltaIndex<H>,
47    target: &[u8],
48    max_output_len: usize,
49) -> Option<Vec<u8>> {
50    const MAX_INITIAL_CAP: usize = 8192; // same as git
51    let mut initial_cap = MAX_INITIAL_CAP.min(target.len() / 2);
52    let max_op_size = 5 + 5 + 1 + H::WINDOW + 7;
53    if initial_cap >= max_output_len {
54        initial_cap = max_output_len + max_op_size + 1;
55    }
56
57    let mut output = Vec::with_capacity(max_output_len.min(initial_cap));
58    write_delta_to(base, index, target, max_output_len, &mut output)?;
59    debug_assert!(output.len() <= max_output_len);
60    #[cfg(debug_assertions)]
61    {
62        let len = get_delta_len(base, index, target, max_output_len).unwrap();
63        assert_eq!(output.len(), len);
64    }
65    Some(output)
66}
67
68/// Creates a reusable hash index from a base buffer.
69///
70/// ```
71/// let base = "This is a pure rust implementation of Git's delta compression algorithm.";
72/// let index = git_pack_delta::create_delta_index(base.as_bytes()).unwrap(); // can be reused for different targets.
73/// let target = base.replace("Git", "git");
74/// let delta = git_pack_delta::write_delta_to_vec(base.as_bytes(), &index, target.as_bytes(), target.len()).unwrap();
75/// assert_eq!(delta.len(), 9);
76/// ```
77pub fn create_delta_index(base: &[u8]) -> Option<DeltaIndex<DefaultHash>> {
78    create_delta_index_custom::<DefaultHash>(base)
79}
80
81/// Creates a delta encoding that can be used to create `target` from `base`.
82///
83/// ```
84/// let base = "This is a pure rust implementation of Git's delta compression algorithm.";
85/// let target = base.replace("Git", "git");
86/// let delta = git_pack_delta::create_delta(base.as_bytes(), target.as_bytes()).unwrap();
87/// assert_eq!(delta.len(), 9);
88/// ```
89pub fn create_delta(base: &[u8], target: &[u8]) -> Option<Vec<u8>> {
90    if target.len() < 18 {
91        return None;
92    }
93    let index = create_delta_index(base)?;
94    let _max_size = target.len() - 1;
95    write_delta_to_vec(base, &index, target, usize::MAX)
96}
97
98/// Recreates the target from the `base` and encoded `delta`.
99///
100/// # Errors
101///
102/// Fails if `delta` is invalid, doesn't match `base`, or the target is too large to fit into memory.
103/// ```
104/// let base = "This is a pure rust implementation of Git's delta compression algorithm.";
105/// let target = base.replace("Git", "git");
106/// let delta = git_pack_delta::create_delta(base.as_bytes(), target.as_bytes()).unwrap();
107/// let target2 = git_pack_delta::patch_delta(base.as_bytes(), &delta).unwrap();
108/// assert_eq!(target.as_bytes(), target2);
109/// ```
110pub fn patch_delta(base: &[u8], delta: &[u8]) -> Result<Vec<u8>, DiffDecodeError> {
111    let mut data = vec![];
112    decode::decode(base, delta, &mut data)?;
113    Ok(data)
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    const SAMPLE_DATA: &str = include_str!("../tests/data/diff-delta.c");
121
122    #[test]
123    fn test_round_trip_rabin() {
124        test_round_trip::<hash::GitRabin>(130);
125    }
126
127    #[test]
128    fn test_round_trip_cyclic_poly32() {
129        test_round_trip::<hash::CyclicPoly32>(130);
130    }
131
132    #[test]
133    fn test_round_trip_cyclic_poly64() {
134        test_round_trip::<hash::CyclicPoly64>(130);
135    }
136
137    #[test]
138    fn example1() {
139        let base = "This is a pure rust implementation of Git's delta compression algorithm.";
140        let target = base.replace("Git", "git");
141        let delta = create_delta(base.as_bytes(), target.as_bytes()).unwrap();
142        assert_eq!(delta.len(), 9);
143        let target2 = patch_delta(base.as_bytes(), &delta).unwrap();
144        assert_eq!(target.as_bytes(), target2);
145    }
146
147    fn test_round_trip<R: RollingHash>(exp: usize) {
148        let base = SAMPLE_DATA.as_bytes();
149        let target = SAMPLE_DATA.to_owned().replace("RABIN", "ROBIN");
150        let target = target.as_bytes();
151
152        let index = create_delta_index_custom::<R>(base).unwrap();
153        let delta = write_delta_to_vec(base, &index, target, usize::MAX).unwrap();
154        let decoded = patch_delta(base, &delta).unwrap();
155        assert_eq!(decoded, target);
156        assert_eq!(delta.len(), exp);
157    }
158}