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
use std::borrow::Cow;
use std::collections::HashMap;
use crate::compare::RopeScanner;
use crate::delta::{Delta, DeltaElement};
use crate::interval::Interval;
use crate::rope::{LinesMetric, Rope, RopeDelta, RopeInfo};
use crate::tree::{Node, NodeInfo};
pub trait Diff<N: NodeInfo> {
fn compute_delta(base: &Node<N>, target: &Node<N>) -> Delta<N>;
}
const MIN_SIZE: usize = 32;
pub struct LineHashDiff;
impl Diff<RopeInfo> for LineHashDiff {
fn compute_delta(base: &Rope, target: &Rope) -> RopeDelta {
let mut builder = DiffBuilder::default();
let mut scanner = RopeScanner::new(base, target);
let (start_offset, diff_end) = scanner.find_min_diff_range();
let target_end = target.len() - diff_end;
if start_offset > 0 {
builder.copy(0, 0, start_offset);
}
if start_offset == base.len() && target.len() == base.len() {
return builder.to_delta(base, target);
}
let line_hashes = make_line_hashes(&base, MIN_SIZE);
let line_count = target.measure::<LinesMetric>() + 1;
let mut matches = Vec::with_capacity(line_count);
let mut targ_line_offset = 0;
let mut prev_base = 0;
let mut needs_subseq = false;
for line in target.lines_raw(start_offset..target_end) {
let non_ws = non_ws_offset(&line);
if line.len() - non_ws >= MIN_SIZE {
if let Some(base_off) = line_hashes.get(&line[non_ws..]) {
let targ_off = targ_line_offset + non_ws;
matches.push((start_offset + targ_off, *base_off));
if *base_off < prev_base {
needs_subseq = true;
}
prev_base = *base_off;
}
}
targ_line_offset += line.len();
}
let longest_subseq =
if needs_subseq { longest_increasing_region_set(&matches) } else { matches };
let mut prev_end = start_offset;
for (targ_off, base_off) in longest_subseq {
if targ_off <= prev_end {
continue;
}
let (left_dist, mut right_dist) =
expand_match(base, target, base_off, targ_off, prev_end);
right_dist = right_dist.min(target_end - targ_off);
let targ_start = targ_off - left_dist;
let base_start = base_off - left_dist;
let len = left_dist + right_dist;
prev_end = targ_start + len;
builder.copy(base_start, targ_start, len);
}
if diff_end > 0 {
builder.copy(base.len() - diff_end, target.len() - diff_end, diff_end);
}
builder.to_delta(base, target)
}
}
fn expand_match(
base: &Rope,
target: &Rope,
base_off: usize,
targ_off: usize,
prev_match_targ_end: usize,
) -> (usize, usize) {
let mut scanner = RopeScanner::new(base, target);
let max_left = targ_off - prev_match_targ_end;
let start = scanner.find_ne_char_back(base_off, targ_off, max_left);
debug_assert!(start <= max_left, "{} <= {}", start, max_left);
let end = scanner.find_ne_char(base_off, targ_off, None);
(start.min(max_left), end)
}
fn longest_increasing_region_set(items: &[(usize, usize)]) -> Vec<(usize, usize)> {
let mut result = vec![0];
let mut prev_chain = vec![0; items.len()];
for i in 1..items.len() {
let last_idx = *result.last().unwrap();
if items[last_idx].1 < items[i].1 {
prev_chain[i] = last_idx;
result.push(i);
continue;
}
let next_idx = match result.binary_search_by(|&j| items[j].1.cmp(&items[i].1)) {
Ok(_) => continue,
Err(idx) => idx,
};
if items[i].1 < items[result[next_idx]].1 {
if next_idx > 0 {
prev_chain[i] = result[next_idx - 1];
}
result[next_idx] = i;
}
}
let mut u = result.len();
let mut v = *result.last().unwrap();
while u != 0 {
u -= 1;
result[u] = v;
v = prev_chain[v];
}
result.iter().map(|i| items[*i]).collect()
}
#[inline]
fn non_ws_offset(s: &str) -> usize {
s.as_bytes().iter().take_while(|b| **b == b' ' || **b == b'\t').count()
}
#[derive(Debug, Clone, Copy)]
struct DiffOp {
target_idx: usize,
base_idx: usize,
len: usize,
}
#[derive(Debug, Clone, Default)]
pub struct DiffBuilder {
ops: Vec<DiffOp>,
}
impl DiffBuilder {
fn copy(&mut self, base: usize, target: usize, len: usize) {
if let Some(prev) = self.ops.last_mut() {
let prev_end = prev.target_idx + prev.len;
let base_end = prev.base_idx + prev.len;
assert!(prev_end <= target, "{} <= {} prev {:?}", prev_end, target, prev);
if prev_end == target && base_end == base {
prev.len += len;
return;
}
}
self.ops.push(DiffOp { target_idx: target, base_idx: base, len })
}
fn to_delta(self, base: &Rope, target: &Rope) -> RopeDelta {
let mut els = Vec::with_capacity(self.ops.len() * 2);
let mut targ_pos = 0;
for DiffOp { base_idx, target_idx, len } in self.ops {
if target_idx > targ_pos {
let iv = Interval::new(targ_pos, target_idx);
els.push(DeltaElement::Insert(target.subseq(iv)));
}
els.push(DeltaElement::Copy(base_idx, base_idx + len));
targ_pos = target_idx + len;
}
if targ_pos < target.len() {
let iv = Interval::new(targ_pos, target.len());
els.push(DeltaElement::Insert(target.subseq(iv)));
}
Delta { els, base_len: base.len() }
}
}
fn make_line_hashes<'a>(base: &'a Rope, min_size: usize) -> HashMap<Cow<'a, str>, usize> {
let mut offset = 0;
let mut line_hashes = HashMap::with_capacity(base.len() / 60);
for line in base.lines_raw(..) {
let non_ws = non_ws_offset(&line);
if line.len() - non_ws >= min_size {
let cow = match line {
Cow::Owned(ref s) => Cow::Owned(s[non_ws..].to_string()),
Cow::Borrowed(s) => Cow::Borrowed(&s[non_ws..]),
};
line_hashes.insert(cow, offset + non_ws);
}
offset += line.len();
}
line_hashes
}
#[cfg(test)]
mod tests {
use super::*;
static SMALL_ONE: &str = "This adds FixedSizeAdler32, that has a size set at construction, and keeps bytes in a cyclic buffer of that size to be removed when it fills up.
Current logic (and implementing Write) might be too much, since bytes will probably always be fed one by one anyway. Otherwise a faster way of removing a sequence might be needed (one by one is inefficient).";
static SMALL_TWO: &str = "This adds some function, I guess?, that has a size set at construction, and keeps bytes in a cyclic buffer of that size to be ground up and injested when it fills up.
Currently my sense of smell (and the pain of implementing Write) might be too much, since bytes will probably always be fed one by one anyway. Otherwise crying might be needed (one by one is inefficient).";
static INTERVAL_STR: &str = include_str!("../src/interval.rs");
static BREAKS_STR: &str = include_str!("../src/breaks.rs");
#[test]
fn diff_smoke_test() {
let one = SMALL_ONE.into();
let two = SMALL_TWO.into();
let delta = LineHashDiff::compute_delta(&one, &two);
println!("delta: {:?}", &delta);
let result = delta.apply(&one);
assert_eq!(result, two);
let delta = LineHashDiff::compute_delta(&one, &two);
println!("delta: {:?}", &delta);
let result = delta.apply(&one);
assert_eq!(result, two);
}
#[test]
fn test_larger_diff() {
let one = INTERVAL_STR.into();
let two = BREAKS_STR.into();
let delta = LineHashDiff::compute_delta(&one, &two);
let result = delta.apply(&one);
assert_eq!(String::from(result), String::from(two));
}
}