Debian Codegraph @

rust/hg-core/src/revlog/diff.rs

raw
1 //! Utilities to compute diff for and with Revlogs.
2 use imara_diff::Algorithm;
3 use imara_diff::Diff;
4 use imara_diff::InternedInput;
5 use imara_diff::TokenSource;
6
7 use super::inner_revlog::InnerRevlog;
8 use super::inner_revlog::SingleRevisionCache;
9 use super::patch;
10 use super::patch::DeltaPiece;
11 use super::patch::PlainDeltaPiece;
12 use super::RevlogEntry;
13 use super::RevlogError;
14 use crate::utils::u32_u;
15 use crate::utils::u_i32;
16 use crate::utils::u_u32;
17 use crate::utils::RawData;
18 use crate::Revision;
19
20 /// A windows of different data when computing a delta
21 ///
22 /// It keep a reference to the full "new" data to be able to extend them.
23 pub(super) struct DeltaCursor<'a> {
24 old: (u32, u32),
25 new: (u32, u32),
26 data: &'a [u8],
27 }
28
29 impl<'a> DeltaCursor<'a> {
30 pub fn new(
31 old_start: u32,
32 old_end: u32,
33 new_start: u32,
34 new_end: u32,
35 full_new_data: &'a [u8],
36 ) -> Self {
37 assert!(
38 !(old_start == old_end && new_start == new_end),
39 "{} == {} && {} == {}",
40 old_start,
41 old_end,
42 new_start,
43 new_end,
44 );
45 DeltaCursor {
46 old: (old_start, old_end),
47 new: (new_start, new_end),
48 data: full_new_data,
49 }
50 }
51
52 pub fn ends_at(&self, offset: u32) -> bool {
53 self.old.1 == offset
54 }
55
56 pub fn extend(&mut self, old_size: u32, new_size: u32) {
57 self.old.1 += old_size;
58 self.new.1 += new_size;
59 }
60
61 /// flush a non empty cursor
62 pub fn into_piece(self) -> PlainDeltaPiece<'a> {
63 let start = self.old.0;
64 let end = self.old.1;
65 let d_start = u32_u(self.new.0);
66 let d_end = u32_u(self.new.1);
67 let data = &self.data[d_start..d_end];
68 PlainDeltaPiece { start, end, data }
69 }
70 }
71
72 impl std::fmt::Debug for DeltaCursor<'_> {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 f.debug_struct("DeltaCursor")
75 .field("old", &self.old)
76 .field("old_size", &(self.old.1 - self.old.0))
77 .field("new", &self.new)
78 .field("new_size", &(self.new.1 - self.new.0))
79 .finish()
80 }
81 }
82
83 // note: 512 was picked somewhat arbitrarily and could probably be tuned.
84 // The value need to be big enough to the compiler to decide to use the most
85 // efficient SIMD vectorization at hand. Overshooting a bit is not dramatic as a
86 // manifest line is in the 100 bytes order of magnitude.
87 pub(crate) const CMP_BLK_SIZE: usize = 512;
88
89 /// return a lower bound estimate of the size of a line-aligned prefix
90 ///
91 /// For that many bytes, we garantee all lines are the same. A few consecutive
92 /// lines might still be identical after that point.
93 pub(crate) fn lines_prefix_size_low(left: &[u8], right: &[u8]) -> usize {
94 lines_prefix_size_low_chunk::<CMP_BLK_SIZE>(left, right)
95 }
96
97 fn lines_prefix_size_low_chunk<const N: usize>(
98 left: &[u8],
99 right: &[u8],
100 ) -> usize {
101 let chunk_count =
102 std::iter::zip(left.chunks_exact(N), right.chunks_exact(N))
103 .take_while(|(l, r)| l == r)
104 .count();
105 let chunk_off = chunk_count * N;
106 match memchr::memrchr(b'\n', &left[..chunk_off]) {
107 None => 0,
108 Some(pos) => pos + 1,
109 }
110 }
111
112 /// Return the size of a line-aligned identical suffix
113 ///
114 /// The suffix might not be minimal
115 pub fn lines_suffix_size_low(left: &[u8], right: &[u8]) -> usize {
116 lines_suffix_size_low_chunk::<CMP_BLK_SIZE>(left, right)
117 }
118
119 fn lines_suffix_size_low_chunk<const N: usize>(
120 left: &[u8],
121 right: &[u8],
122 ) -> usize {
123 let chunk_count =
124 std::iter::zip(left.rchunks_exact(N), right.rchunks_exact(N))
125 .take_while(|(l, r)| l == r)
126 .count();
127 let size = chunk_count * N;
128 match memchr::memchr(b'\n', &left[left.len() - size..]) {
129 None => 0,
130 Some(pos) => size - (pos + 1),
131 }
132 }
133
134 /// Estimation of the number of bytes per lines
135 ///
136 /// This is used to infer the number of line we can expect for a given full text
137 ///
138 /// The value was arbitrarily picked and should probably be refined at some
139 /// point.
140 pub(crate) const MIN_AVG_LINE_SIZE: usize = 10;
141
142 /// Tracks the starting position of each line of a full text
143 ///
144 /// Also holds an abstract final line marking the end of the full text.
145 struct Lines<'a> {
146 /// The full text.
147 data: &'a [u8],
148 /// Starting position of each lines.
149 offsets: Vec<usize>,
150 }
151
152 impl<'a> Lines<'a> {
153 fn new(data: &'a [u8]) -> Self {
154 let mut offsets =
155 Vec::with_capacity(data.len() / MIN_AVG_LINE_SIZE + 2);
156 // TODO: filling the vec at tokenization time would avoid walking the
157 // memory twice
158 offsets.push(0);
159 offsets.extend(memchr::memchr_iter(b'\n', data).map(|o| o + 1));
160 if let Some(c) = data.last() {
161 if *c != b'\n' {
162 offsets.push(data.len());
163 }
164 }
165 Self { data, offsets }
166 }
167
168 /// The starting position of the `idx`'th line.
169 fn offset(&self, idx: u32) -> u32 {
170 u_u32(self.offsets[u32_u(idx)])
171 }
172 }
173
174 /// iterator over each line of a full text.
175 struct IterLines<'a> {
176 text: &'a Lines<'a>,
177 idx: u32,
178 }
179
180 impl<'a> IterLines<'a> {
181 fn new(text: &'a Lines) -> Self {
182 Self { text, idx: 1 }
183 }
184 }
185
186 impl<'a> Iterator for IterLines<'a> {
187 type Item = &'a [u8];
188
189 fn next(&mut self) -> Option<Self::Item> {
190 if u32_u(self.idx) < self.text.offsets.len() {
191 let start = self.text.offset(self.idx - 1);
192 let end = self.text.offset(self.idx);
193 let next = &self.text.data[u32_u(start)..u32_u(end)];
194 self.idx += 1;
195 Some(next)
196 } else {
197 None
198 }
199 }
200 }
201
202 /// By default, a line diff is produced for slice of bytes
203 impl<'a> TokenSource for &'a Lines<'a> {
204 type Token = &'a [u8];
205 type Tokenizer = IterLines<'a>;
206
207 fn tokenize(&self) -> Self::Tokenizer {
208 IterLines::new(self)
209 }
210
211 fn estimate_tokens(&self) -> u32 {
212 u_u32(self.offsets.len())
213 }
214 }
215
216 /// Compute a delta between m1 an m2.
217 ///
218 /// The delta is line aligned.
219 pub fn text_delta(m1: &[u8], m2: &[u8]) -> Vec<u8> {
220 text_delta_with_offset(0, m1, m2)
221 }
222 pub(super) fn text_delta_with_offset(
223 offset: u32,
224 m1: &[u8],
225 m2: &[u8],
226 ) -> Vec<u8> {
227 let mut delta = vec![];
228
229 let offset: usize = offset.try_into().expect("16bits computer?");
230 let prefix_size = lines_prefix_size_low(m1, m2);
231 let suffix_size =
232 lines_suffix_size_low(&m1[prefix_size..], &m2[prefix_size..]);
233
234 match (
235 &m1[prefix_size..m1.len() - suffix_size],
236 &m2[prefix_size..m2.len() - suffix_size],
237 ) {
238 ([], []) => (),
239 (m, []) => all_deleted(offset + prefix_size, m, &mut delta),
240 ([], m) => all_created(offset + prefix_size, m, &mut delta),
241 (sub_1, sub_2) => {
242 text_delta_inner(offset + prefix_size, sub_1, sub_2, &mut delta)
243 }
244 }
245 delta
246 }
247
248 fn all_created(prefix_size: usize, content: &[u8], delta: &mut Vec<u8>) {
249 let start = u_u32(prefix_size);
250 PlainDeltaPiece { start, end: start, data: content }.write(delta)
251 }
252
253 fn all_deleted(prefix_size: usize, deleted: &[u8], delta: &mut Vec<u8>) {
254 let start = u_u32(prefix_size);
255 let end = start + u_u32(deleted.len());
256 PlainDeltaPiece { start, end, data: &[] }.write(delta)
257 }
258
259 /// The main part of [`text_delta`] extracted for clarity
260 ///
261 /// This is the part actually diffing lines.
262 fn text_delta_inner(
263 prefix_size: usize,
264 m1: &[u8],
265 m2: &[u8],
266 delta: &mut Vec<u8>,
267 ) {
268 let skip: u32 = u_u32(prefix_size);
269 let mut cursor: Option<DeltaCursor> = None;
270 let t1 = Lines::new(m1);
271 let t2 = Lines::new(m2);
272 let input = InternedInput::new(&t1, &t2);
273 // XXX consider testing other algorithm at some point
274 let diff = Diff::compute(Algorithm::Myers, &input);
275 for h in diff.hunks() {
276 assert!(
277 !(h.before.start == h.before.end && h.after.start == h.after.end),
278 "{:?}",
279 h,
280 );
281 let start = skip + t1.offset(h.before.start);
282 let end = skip + t1.offset(h.before.end);
283 let content_start = t2.offset(h.after.start);
284 let content_end = t2.offset(h.after.end);
285 cursor = Some(if let Some(mut c) = cursor.take() {
286 if c.ends_at(start) {
287 c.extend(end - start, content_end - content_start);
288 c
289 } else {
290 c.into_piece().write(delta);
291 DeltaCursor::new(start, end, content_start, content_end, m2)
292 }
293 } else {
294 DeltaCursor::new(start, end, content_start, content_end, m2)
295 });
296 }
297 if let Some(last) = cursor {
298 last.into_piece().write(delta)
299 }
300 }
301
302 /// hold state and data useful to computing the delta of two revisions with some
303 /// common part for their delta chain.
304 pub(super) struct RevDeltaState<'irl> {
305 irl: &'irl InnerRevlog,
306 cache: Option<SingleRevisionCache>,
307 common_rev: Revision,
308 old_rev: Revision,
309 new_rev: Revision,
310 /// All the bytes used in the combined delta chain
311 chunks: Vec<RawData>,
312 /// The chain associated with each chunks in "chunks
313 /// 0: common chain
314 /// 1: old chain
315 /// 2: new chain
316 chunk_users: Vec<u8>,
317 /// The number of chunks in each chain
318 ///
319 /// (common, old, new)
320 chunk_counts: (usize, usize, usize),
321 extra_delta: Option<&'irl [u8]>,
322 }
323
324 /// hold the necessary reference to compute the delta between two content (from
325 /// a `RevDeltaState`)
326 pub(super) struct Prepared<'state, D>
327 where
328 D: patch::DeltaPiece<'state>,
329 {
330 pub(super) common_rev: Revision,
331 pub(super) base_text: &'state [u8],
332 pub(super) common_delta: patch::Delta<'state, D>,
333 pub(super) common_size: u32,
334 pub(super) old_delta: patch::Delta<'state, D>,
335 pub(super) old_size: u32,
336 pub(super) new_delta: patch::Delta<'state, D>,
337 pub(super) new_size: u32,
338 }
339
340 impl<'irl> RevDeltaState<'irl> {
341 pub(super) fn new(
342 irl: &'irl InnerRevlog,
343 cache: Option<SingleRevisionCache>,
344 common_count: usize,
345 cached_idx: Option<usize>,
346 delta_chain_1: Vec<Revision>,
347 delta_chain_2: Vec<Revision>,
348 extra_delta: Option<&'irl [u8]>,
349 ) -> Result<Self, RevlogError> {
350 let common_rev = delta_chain_1[common_count - 1];
351 // note: rev_# might be different than the source if empty delta where
352 // trimed from the chain. This has no impact of the computation
353 // of the delta.
354 let rev_1 = delta_chain_1[delta_chain_1.len() - 1];
355 let rev_2 = delta_chain_2[delta_chain_2.len() - 1];
356 let entry_c = &irl.get_entry(common_rev)?;
357 let entry_1 = &irl.get_entry(rev_1)?;
358 let entry_2 = &irl.get_entry(rev_2)?;
359 let rev_size = |e: &RevlogEntry| e.uncompressed_len().unwrap_or(0u32);
360
361 // estimate the total chunks size from the revisions size
362 let size_c = rev_size(entry_c);
363 let size_1 = rev_size(entry_1);
364 let size_2 = rev_size(entry_2);
365 let t_size = Some((size_1 as u64 + size_2 as u64) * 4);
366 irl.seen_file_size(u32_u(size_c.max(size_1.max(size_2))));
367
368 // Merge the two delta chain into a single Vec
369 //
370 // This allow for fetching all of them in one go. We add a "user" value
371 // next to it to be able to know if a chunk is to be used for
372 // the common chain, the old chain or the new chain.
373 let (cache, common_start) = if let Some(cached_idx) = cached_idx {
374 (cache, cached_idx + 1)
375 } else {
376 (None, 0)
377 };
378 let chain_1_cnt = delta_chain_1.len() - common_count;
379 let chain_2_cnt = delta_chain_2.len() - common_count;
380 let common_cnt = common_count - common_start;
381 let fetch_cnt = common_cnt + chain_1_cnt + chain_2_cnt;
382
383 let mut all_revs = Vec::with_capacity(fetch_cnt);
384 all_revs.extend(
385 (delta_chain_1[common_start..common_count]).iter().map(|r| (*r, 0)),
386 );
387 all_revs
388 .extend((delta_chain_1[common_count..]).iter().map(|r| (*r, 1)));
389 all_revs
390 .extend((delta_chain_2[common_count..]).iter().map(|r| (*r, 2)));
391 // sort them as `irl.chunks` expect them to to be sorted
392 all_revs.sort();
393
394 let fetch_revs: Vec<_> = all_revs.iter().map(|(r, _)| *r).collect();
395 let chunk_users: Vec<_> = all_revs.iter().map(|(_, u)| *u).collect();
396 let chunks = irl.chunks(&fetch_revs, t_size)?;
397
398 Ok(Self {
399 irl,
400 cache,
401 common_rev,
402 old_rev: rev_1,
403 new_rev: rev_2,
404 chunks,
405 chunk_users,
406 chunk_counts: (common_cnt, chain_1_cnt, chain_2_cnt),
407 extra_delta,
408 })
409 }
410
411 /// Return the core element to compute a delta from two common delta chain.
412 pub(super) fn prepare<D>(
413 &'irl mut self,
414 ) -> Result<Prepared<'irl, D>, RevlogError>
415 where
416 D: patch::DeltaPiece<'irl>,
417 {
418 // determine the base_text and when the delta start in the chunks
419 let (base_text, chain_start): (&[u8], usize) =
420 if let Some(cache) = &self.cache {
421 (cache, 0)
422 } else {
423 (&self.chunks[0], 1)
424 };
425
426 // gather delta from all chains.
427 let mut common_deltas = Vec::with_capacity(self.chunk_counts.0);
428 let mut old_deltas = Vec::with_capacity(self.chunk_counts.1);
429 let mut new_deltas = Vec::with_capacity(self.chunk_counts.2);
430 let chains = [&mut common_deltas, &mut old_deltas, &mut new_deltas];
431 for (idx, (chunk, src)) in std::iter::zip(
432 &self.chunks[chain_start..],
433 &self.chunk_users[chain_start..],
434 )
435 .enumerate()
436 {
437 let d = patch::Delta::new_rich(u_u32(idx + 1), chunk)?;
438 let c: usize = (*src).into();
439 chains[c].push(d)
440 }
441 // inject the extra delta if any
442 if let Some(delta) = &self.extra_delta {
443 let extra_id = u_u32(self.chunks.len() + 1);
444 let d = patch::Delta::new_rich(extra_id, delta)?;
445 new_deltas.push(d)
446 }
447 // get common base_text, delta, and size
448 let common_delta = patch::fold_deltas(common_deltas);
449 let size_c: u32 = self
450 .irl
451 .get_entry(self.common_rev)?
452 .uncompressed_len()
453 .unwrap_or_else(|| {
454 let size = u_i32(base_text.len());
455 let patched_size = size - common_delta.len_diff();
456 assert!(patched_size >= 0);
457 patched_size as u32
458 });
459
460 // old delta and size
461 let old_delta = patch::fold_deltas(old_deltas);
462 let size_old: u32 = self
463 .irl
464 .get_entry(self.old_rev)?
465 .uncompressed_len()
466 .unwrap_or_else(|| {
467 let patched_size = size_c as i32 - old_delta.len_diff();
468 assert!(patched_size >= 0);
469 patched_size as u32
470 });
471 // new delta and size
472 let new_delta = patch::fold_deltas(new_deltas);
473 let size_new: u32 = self
474 .irl
475 .get_entry(self.new_rev)?
476 .uncompressed_len()
477 .unwrap_or_else(|| {
478 let patched_size = size_c as i32 - new_delta.len_diff();
479 assert!(patched_size >= 0);
480 patched_size as u32
481 });
482
483 Ok(Prepared {
484 common_rev: self.common_rev,
485 base_text,
486 common_delta,
487 common_size: size_c,
488 old_delta,
489 old_size: size_old,
490 new_delta,
491 new_size: size_new,
492 })
493 }
494 }