Debian Codegraph @

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

raw
1 //! Gather code around processing and applying delta
2 //!
3 //! Terminology:
4 //!
5 //! **Full-Text:** a blob of bytes that consistitute a consisten content
6 //! (usually a revision)
7 //!
8 //! **Delta:** A series of "DeltaPiece" that can be applied to a Full-Text" to
9 //! produce another "Full-Text".
10 //!
11 //! **DeltaPiece:** An atomic unit that replace a section of the *old*
12 //! "Full-Text" with another.
13 //!
14 //! **Delta-Chain:** A "Full-Text" followed by a list of Delta.
15 //!
16 //! **Delta-Base:** The content a Delta applies to. It can be an explicite
17 //! Full-Text or a Delta-Chain.
18 use byteorder::BigEndian;
19 use byteorder::ByteOrder;
20
21 use super::inner_revlog::RevisionBuffer;
22 use crate::revlog::CoreRevisionBuffer;
23 use crate::revlog::RevlogError;
24 use crate::utils::u32_u;
25 use crate::utils::u_u32;
26
27 /// A piece of data to insert, delete or replace in a Delta
28 pub(super) trait DeltaPiece<'a>: Clone {
29 /// build a DeltaPiece from extra information
30 ///
31 /// The implementation is free to discard the information it doesn't need.
32 fn new_rich(
33 src: SrcToken,
34 start: u32,
35 end: u32,
36 data_pos: u32,
37 data: &'a [u8],
38 ) -> Self;
39
40 /// The start position of the chunk of data to replace
41 fn start(&self) -> u32;
42
43 /// The end position of the chunk of data to replace (open end interval)
44 fn end(&self) -> u32;
45
46 /// The data replacing the chunk
47 fn data(&self) -> &'a [u8];
48
49 /// Length of the replaced date.
50 fn size(&self) -> u32;
51
52 /// Length of the replaced date.
53 fn replaced_len(&self) -> u32 {
54 self.end() - self.start()
55 }
56
57 /// Length of the replaced date.
58 fn is_empty(&self) -> bool {
59 self.replaced_len() == 0 && self.size() == 0
60 }
61
62 /// Length difference between the replacing data and the replaced data.
63 fn len_diff(&self) -> i32 {
64 self.size() as i32 - self.replaced_len() as i32
65 }
66
67 /// Adjusted start of the data to replace.
68 ///
69 /// The offset, taking into account the growth/shrinkage of data
70 /// induced by previously applied DeltaPiece.
71 fn start_offset_by(&self, offset: i32) -> u32 {
72 let start = self.start() as i32 + offset;
73 assert!(start >= 0, "negative chunk start should never happen");
74 start as u32
75 }
76
77 /// Adjusted end of the data to replace.
78 ///
79 /// The offset, taking into account the growth/shrinkage of data
80 /// induced by previously applied DeltaPiece.
81 fn end_offset_by(&self, offset: i32) -> u32 {
82 self.start_offset_by(offset) + self.size()
83 }
84
85 /// cut this DeltaPiece into two
86 ///
87 /// The `cut_start` argument refer to the first index in `self.data()` that
88 /// goes in the first DeltaPiece. self is modified in place to contains
89 /// the second DeltaPiece.
90 fn cut_at(&mut self, cut_start: u32) -> Self;
91
92 /// remove the `size` first bytes from the this DeltaPiece
93 fn trim_prefix(&mut self, size: u32) -> i32;
94
95 /// adjust this DeltaPiece by the given offset
96 ///
97 /// (the offset is substracted to the piece `start` and `end`).
98 fn apply_offset(&self, start_offset: i32, end_offset: i32) -> Self;
99
100 /// push a single DeltaPiece inside a Delta, ignoring empty ones
101 fn write(self, delta: &mut Vec<u8>) {
102 if self.replaced_len() == 0 && self.size() == 0 {
103 return;
104 }
105 debug_assert!(
106 !(self.start() == self.end() && self.size() == 0),
107 "won't write empty chunk"
108 );
109 delta.extend_from_slice(&u32::to_be_bytes(self.start()));
110 delta.extend_from_slice(&u32::to_be_bytes(self.end()));
111 delta.extend_from_slice(&u32::to_be_bytes(self.size()));
112 delta.extend_from_slice(self.data());
113 }
114 }
115
116 /// A piece of data to insert, delete or replace in a Delta
117 ///
118 /// A DeltaPiece is:
119 /// - an insertion when `!data.is_empty() && start == end`
120 /// - an deletion when `data.is_empty() && start < end`
121 /// - a replacement when `!data.is_empty() && start < end`
122 /// - not doing anything when `data.is_empty() && start == end`
123 #[derive(Clone)]
124 pub(crate) struct PlainDeltaPiece<'a> {
125 /// The start position of the chunk of data to replace
126 pub(crate) start: u32,
127 /// The end position of the chunk of data to replace (open end interval)
128 pub(crate) end: u32,
129 /// The data replacing the chunk
130 pub(crate) data: &'a [u8],
131 }
132
133 impl<'a> DeltaPiece<'a> for PlainDeltaPiece<'a> {
134 fn new_rich(
135 _src: SrcToken,
136 start: u32,
137 end: u32,
138 _data_pos: u32,
139 data: &'a [u8],
140 ) -> Self {
141 Self { start, end, data }
142 }
143
144 /// The start position of the chunk of data to replace
145 fn start(&self) -> u32 {
146 self.start
147 }
148
149 /// The end position of the chunk of data to replace (open end interval)
150 fn end(&self) -> u32 {
151 self.end
152 }
153
154 /// The data replacing the chunk
155 fn data(&self) -> &'a [u8] {
156 self.data
157 }
158
159 /// Length of the replaced date.
160 fn size(&self) -> u32 {
161 u_u32(self.data.len())
162 }
163
164 /// cut this DeltaPiece into two
165 ///
166 /// The `cut_start` argument refer to the first index in `self.data()` that
167 /// needs to go in the second DeltaPiece
168 fn cut_at(&mut self, cut_start: u32) -> Self {
169 assert!(cut_start > 0);
170 assert!(cut_start < self.size());
171
172 let (left_data, right_data) = self.data.split_at(u32_u(cut_start));
173 self.data = right_data;
174 PlainDeltaPiece {
175 // there is no need to think too hard about which section of the
176 // replaced part goes in the prefix and which goes in
177 // the suffix. So lets use a zero size replacement for
178 // the suffix
179 start: self.start,
180 end: self.start,
181 data: left_data,
182 }
183 }
184
185 fn trim_prefix(&mut self, size: u32) -> i32 {
186 assert!(size < self.size());
187 self.data = &self.data[u32_u(size)..];
188 let old_replace = self.replaced_len();
189 if old_replace < size {
190 self.start = self.end;
191 size as i32 - old_replace as i32
192 } else {
193 self.start += size;
194 0
195 }
196 }
197
198 fn apply_offset(&self, start_offset: i32, end_offset: i32) -> Self {
199 Self {
200 start: (self.start as i32 - start_offset) as u32,
201 end: (self.end as i32 - end_offset) as u32,
202 data: self.data,
203 }
204 }
205 }
206
207 impl std::fmt::Debug for PlainDeltaPiece<'_> {
208 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209 f.debug_struct("PlainDeltaPiece")
210 .field("start", &self.start)
211 .field("end", &self.end)
212 .field("size", &self.data.len())
213 .finish()
214 }
215 }
216
217 /// An identifier for which Chunk a DeltaPiece comes from.
218 ///
219 /// Used within RichDeltaPiece
220 ///
221 /// The 0 value is usually reserved for the base-text
222 type SrcToken = u32;
223
224 /// A DeltaPiece with information about source and position within that source
225 #[derive(Clone, Debug)]
226 pub(crate) struct RichDeltaPiece<'a> {
227 pub inner: PlainDeltaPiece<'a>,
228 pub src: SrcToken,
229 pub data_pos: u32,
230 }
231
232 impl RichDeltaPiece<'_> {
233 pub(super) fn data_start(&self) -> u32 {
234 self.data_pos
235 }
236
237 pub(super) fn data_end(&self) -> u32 {
238 self.data_start() + self.size()
239 }
240 }
241
242 impl<'a> DeltaPiece<'a> for RichDeltaPiece<'a> {
243 fn new_rich(
244 src: SrcToken,
245 start: u32,
246 end: u32,
247 data_pos: u32,
248 data: &'a [u8],
249 ) -> Self {
250 let inner = PlainDeltaPiece::new_rich(src, start, end, data_pos, data);
251 Self { inner, src, data_pos }
252 }
253 /// The start position of the chunk of data to replace
254 fn start(&self) -> u32 {
255 self.inner.start()
256 }
257
258 /// The end position of the chunk of data to replace (open end interval)
259 fn end(&self) -> u32 {
260 self.inner.end()
261 }
262
263 /// The data replacing the chunk
264 fn data(&self) -> &'a [u8] {
265 self.inner.data()
266 }
267
268 /// Length of the replaced date.
269 fn size(&self) -> u32 {
270 self.inner.size()
271 }
272
273 /// cut this DeltaPiece into two
274 ///
275 /// The `cut_start` argument refer to the first index in `self.data()` that
276 /// needs to go in the second DeltaPiece
277 fn cut_at(&mut self, cut_start: u32) -> Self {
278 let old_pos = self.data_pos;
279 self.data_pos += cut_start;
280 let right = self.inner.cut_at(cut_start);
281 Self { inner: right, src: self.src, data_pos: old_pos }
282 }
283
284 fn trim_prefix(&mut self, size: u32) -> i32 {
285 self.data_pos += size;
286 self.inner.trim_prefix(size)
287 }
288
289 fn apply_offset(&self, start_offset: i32, end_offset: i32) -> Self {
290 Self {
291 inner: self.inner.apply_offset(start_offset, end_offset),
292 src: self.src,
293 data_pos: self.data_pos,
294 }
295 }
296 }
297
298 /// The delta between two revisions data.
299 #[derive(Debug, Clone)]
300 pub(super) struct Delta<'a, P>
301 where
302 P: DeltaPiece<'a>,
303 {
304 /// A collection of DeltaPiece to apply.
305 ///
306 /// Those DeltaPiece are:
307 /// - ordered from the left-most replacement to the right-most replacement
308 /// - non-overlapping, meaning that two chucks can not change the same
309 /// chunk of the patched data
310 pub(crate) chunks: Vec<P>,
311 phantom: std::marker::PhantomData<&'a P>,
312 }
313
314 impl<'a> Delta<'a, PlainDeltaPiece<'a>> {
315 /// Create a `Delta` from bytes.
316 pub fn new(data: &'a [u8]) -> Result<Self, RevlogError> {
317 Self::new_rich(u32::MAX, data)
318 }
319 }
320
321 impl<'a, D> Delta<'a, D>
322 where
323 D: DeltaPiece<'a>,
324 {
325 pub fn new_rich(
326 src: SrcToken,
327 data: &'a [u8],
328 ) -> Result<Self, RevlogError> {
329 let mut chunks = vec![];
330 let mut data = data;
331 let mut data_pos = 0u32;
332 while !data.is_empty() {
333 let start = BigEndian::read_u32(&data[0..]);
334 let end = BigEndian::read_u32(&data[4..]);
335 let len = BigEndian::read_u32(&data[8..]);
336 // bark on end > MAx
337 if start > end {
338 return Err(RevlogError::corrupted("patch cannot be decoded"));
339 }
340 let available = data.len() - 12;
341 if len > u_u32(available + 12) {
342 let error = format!("patch insert more data than available: {len} < {available}");
343 return Err(RevlogError::corrupted(error));
344 }
345 let d = D::new_rich(
346 src,
347 start,
348 end,
349 data_pos,
350 &data[12..12 + (len as usize)],
351 );
352 if !d.is_empty() {
353 chunks.push(d);
354 }
355 data_pos += len;
356 data = &data[12 + (len as usize)..];
357 }
358 Ok(Delta { chunks, phantom: std::marker::PhantomData })
359 }
360
361 /// Creates a patch for a full snapshot, going from nothing to `data`.
362 pub fn full_snapshot(data: &'a [u8]) -> Self {
363 let d = D::new_rich(0, 0, 0, 0, data);
364 Self { chunks: vec![d], phantom: std::marker::PhantomData }
365 }
366 }
367
368 impl<'a, P> Delta<'a, P>
369 where
370 P: DeltaPiece<'a>,
371 {
372 /// Create and empty Delta
373 pub fn empty() -> Self {
374 Self { chunks: vec![], phantom: std::marker::PhantomData }
375 }
376
377 /// True if this piece replace nothing with nothing
378 ///
379 /// Such pieces don't carry information and can be ignored.
380 pub(super) fn is_empty(&self) -> bool {
381 self.chunks.is_empty()
382 }
383
384 /// full text size change implied by this Delta
385 pub(super) fn len_diff(&self) -> i32 {
386 self.chunks.iter().map(|p| p.len_diff()).sum()
387 }
388
389 /// Apply the Delta to some Full-Text,
390 pub fn apply<T>(
391 &self,
392 buffer: &mut dyn RevisionBuffer<Target = T>,
393 initial: &[u8],
394 ) {
395 self.apply_with_offset(buffer, initial, 0)
396 }
397
398 /// Apply the patch to some data with some offset
399 ///
400 /// We apply on a subset of the base content where a prefix of `offset`
401 /// bytes is missing.
402 ///
403 /// The applied patch is still fully apply (and should not overlap with the
404 /// skipped offset).
405 fn apply_with_offset<T>(
406 &self,
407 buffer: &mut dyn RevisionBuffer<Target = T>,
408 initial: &[u8],
409 offset: u32,
410 ) {
411 let mut last: usize = 0;
412 for p in self.chunks.iter() {
413 let o_start = u32_u(p.start() - offset);
414 let slice = &initial[last..o_start];
415 buffer.extend_from_slice(slice);
416 buffer.extend_from_slice(p.data());
417 last = u32_u(p.end() - offset);
418 }
419 buffer.extend_from_slice(&initial[last..]);
420 }
421
422 /// Return a Vec<u8> with the result of a this patch application
423 ///
424 /// The specify offset match the semantic used by `apply_with_offset`.
425 pub(super) fn as_applied(
426 &self,
427 initial: &[u8],
428 offset: u32,
429 target_size: u32,
430 ) -> Vec<u8> {
431 let mut buffer = CoreRevisionBuffer::new();
432 buffer.resize(u32_u(target_size));
433 self.apply_with_offset(&mut buffer, initial, offset);
434 buffer.finish()
435 }
436
437 /// Combine two Delta into a single Delta.
438 ///
439 /// Applying consecutive Delta can lead to waste of time and memory
440 /// as the changes introduced by one Delta can be overridden by the next.
441 /// Combining Delta optimizes the whole patching sequence.
442 ///
443 /// In this method, self is the "low" delta applying so a "base", and
444 /// `other` is the "high" delta, apply to the result of applying "low"
445 /// on "base".
446 pub(super) fn combine(mut self, other: Self) -> Self {
447 if self.chunks.is_empty() {
448 return other;
449 } else if other.chunks.is_empty() {
450 return self;
451 }
452 // every delta-piece in "high" has an opportunity to slice a delta-piece
453 // in "low", creating an extra part. (this is true even if the
454 // "low" delta only have one delta-piece, it could be
455 // sliced over and over in more pieces.
456 //
457 // We precise the Vec that collect the result of the combination to the
458 // maximum number of chunk that might be created.
459 let mut chunks =
460 Vec::with_capacity(self.chunks.len() + 2 * other.chunks.len());
461
462 // Keep track of each growth/shrinkage resulting from applying a chunk
463 // in order to adjust the start/end of subsequent chunks.
464 let mut offset = 0i32;
465
466 // Keep track of the chunk of self.chunks to process.
467 let mut pos = 0;
468
469 let mut push = |p: P| {
470 if !p.is_empty() {
471 chunks.push(p);
472 }
473 };
474
475 // For each chunk of `other`, chunks of `self` are processed
476 // until they start after the end of the current chunk.
477 for high in other.chunks.into_iter() {
478 // Add chunks of `self` that start before this chunk of `other`
479 // without overlap.
480 while pos < self.chunks.len()
481 && self.chunks[pos].end_offset_by(offset) <= high.start()
482 {
483 let first = self.chunks[pos].clone();
484 offset += first.len_diff();
485 push(first);
486 pos += 1;
487 }
488
489 // The current chunk of `self` starts before this chunk of `other`
490 // with overlap.
491 // The left-most part of data is added as an insertion chunk.
492 // The right-most part data is kept in the chunk.
493 if pos < self.chunks.len()
494 && self.chunks[pos].start_offset_by(offset) < high.start()
495 {
496 let current = &mut self.chunks[pos];
497 let cut_point = high.start() - current.start_offset_by(offset);
498 let left = current.cut_at(cut_point);
499 offset += left.len_diff();
500
501 push(left);
502
503 // There is no index incrementation because the right-most part
504 // needs further examination.
505 }
506
507 // At this point remaining chunks of `self` starts after
508 // the current chunk of `other`.
509
510 // `start_offset` will be used to adjust the start of the current
511 // chunk of `other`.
512 // Offset tracking continues with `end_offset` to adjust the end
513 // of the current chunk of `other`.
514 let mut next_offset = offset;
515
516 // Discard the chunks of `self` that are totally overridden
517 // by the current chunk of `other`
518 while pos < self.chunks.len()
519 && self.chunks[pos].end_offset_by(next_offset) <= high.end()
520 {
521 let first = &self.chunks[pos];
522 next_offset += first.len_diff();
523 pos += 1;
524 }
525
526 // Truncate the left-most part of chunk of `self` that overlaps
527 // the current chunk of `other`.
528 if pos < self.chunks.len()
529 && self.chunks[pos].start_offset_by(next_offset) < high.end()
530 {
531 let first = &mut self.chunks[pos];
532
533 let mask_size = high.end() - first.start_offset_by(next_offset);
534 next_offset += first.trim_prefix(mask_size);
535 }
536
537 // Add the chunk of `other` with adjusted position.
538 push(high.apply_offset(offset, next_offset));
539
540 // Go back to normal offset tracking for the next `o` chunk
541 offset = next_offset;
542 }
543
544 // Add remaining chunks of `self`.
545 for elt in &self.chunks[pos..] {
546 push(elt.clone());
547 }
548 Delta { chunks, phantom: std::marker::PhantomData }
549 }
550 }
551
552 impl<'a> Delta<'a, RichDeltaPiece<'a>> {
553 pub(super) fn into_iter_from_base(
554 self,
555 initial: &'a [u8],
556 ) -> impl Iterator<Item = RichDeltaPiece<'a>> {
557 let mut chunks = self.chunks.into_iter();
558 let mut next = chunks.next();
559 let mut last: usize = 0;
560
561 std::iter::from_fn(move || {
562 if let Some(current) = &next {
563 let o_start = u32_u(current.start());
564 if last < o_start {
565 let data = &initial[last..o_start];
566 let pos = last;
567 last = o_start;
568 Some(RichDeltaPiece::new_rich(0, 0, 0, u_u32(pos), data))
569 } else {
570 last = u32_u(current.end());
571 let ret = next.take().expect("in a Some(_) close");
572 next = chunks.next();
573 Some(ret)
574 }
575 } else if last < initial.len() {
576 let data = &initial[last..];
577 let pos = last;
578 last = initial.len();
579 Some(RichDeltaPiece::new_rich(0, 0, 0, u_u32(pos), data))
580 } else {
581 None
582 }
583 })
584 }
585 }
586
587 /// Combine a list of Deltas into a single Delta "optimized".
588 ///
589 /// Content from different Delta will still appears in different
590 /// DeltaPiece, so the result if not "minimal". However it is "optiomized"
591 /// in terms of application as it only contains non overlapping DeltaPiece.
592 pub(super) fn fold_deltas<'a, P>(deltas: Vec<Delta<'a, P>>) -> Delta<'a, P>
593 where
594 P: DeltaPiece<'a>,
595 {
596 let full_size = deltas.len();
597 let mut deltas = deltas.into_iter();
598 fold_deltas_inner(&mut deltas, full_size)
599 }
600
601 fn fold_deltas_inner<'a, P, I>(deltas: &mut I, size: usize) -> Delta<'a, P>
602 where
603 P: DeltaPiece<'a>,
604 I: ExactSizeIterator<Item = Delta<'a, P>>,
605 {
606 if size <= 1 {
607 deltas.next().unwrap_or_else(|| Delta::empty())
608 } else {
609 let left_size = size / 2;
610 let right_size = size - left_size;
611 let left_res = fold_deltas_inner(deltas, left_size);
612 let right_res = fold_deltas_inner(deltas, right_size);
613 left_res.combine(right_res)
614 }
615 }
616
617 /// Build the full data of a revision out its snapshot
618 /// and its deltas.
619 pub fn build_data_from_deltas<T>(
620 buffer: &mut dyn RevisionBuffer<Target = T>,
621 snapshot: &[u8],
622 deltas: &[impl AsRef<[u8]>],
623 ) -> Result<(), RevlogError> {
624 if deltas.is_empty() {
625 buffer.extend_from_slice(snapshot);
626 return Ok(());
627 }
628 let patches = self::deltas(deltas);
629 let patch = fold_deltas(patches?);
630 patch.apply(buffer, snapshot);
631 Ok(())
632 }
633
634 /// Parse the Deltas from their binary form.
635 pub(super) fn deltas<D>(
636 deltas: &[D],
637 ) -> Result<Vec<Delta<PlainDeltaPiece>>, RevlogError>
638 where
639 D: AsRef<[u8]>,
640 {
641 deltas.iter().map(|d| Delta::new(d.as_ref())).collect()
642 }
643
644 /// apply a chain of Delta in binary form to a Full-Text
645 #[allow(dead_code)]
646 pub(super) fn apply_chain<D>(
647 full_text: &[u8],
648 delta_chain: &[D],
649 target_size: u32,
650 ) -> Result<Vec<u8>, RevlogError>
651 where
652 D: AsRef<[u8]>,
653 {
654 let deltas = deltas(delta_chain)?;
655 let projected = fold_deltas(deltas);
656 Ok(projected.as_applied(full_text, 0, target_size))
657 }
658
659 #[cfg(test)]
660 mod tests {
661 use rand::prelude::*;
662 use rand::SeedableRng;
663
664 use super::*;
665
666 impl PartialOrd for TestChain {
667 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
668 Some(self.cmp(other))
669 }
670 }
671
672 const MIN_SIZE: usize = 1;
673 const MAX_SIZE: usize = 10;
674
675 /// represent a chain of deltas usable for test.
676 ///
677 /// - the full text size is alway betwen 1 and 10,
678 /// - content from the full text are bytes in the [0, 9] range,
679 /// - content from patch N are bytes in the [10 * N, 10 * N + 9].
680 #[derive(Debug, Clone, Eq, PartialEq)]
681 struct TestChain {
682 /// the "Full-Text" initial size
683 initial_size: u8,
684 /// The "Deltas" involved in the chain
685 deltas: Vec<TestDelta>,
686 }
687
688 #[derive(Debug, Clone, Eq, PartialEq)]
689 struct TestDelta {
690 /// The size of the Full-Text this Delta applies to.
691 src_size: u8,
692 /// The size of the Full-Text resulting from applying this delta.
693 dst_size: u8,
694 /// The Delta-Pieces that compose this delta (alway have at least one).
695 pieces: Vec<TestPiece>,
696 }
697
698 #[derive(Debug, Clone, Eq, PartialEq)]
699 struct TestPiece {
700 /// offset in the "Base" we start replacing.
701 pos: u8,
702 /// the size of the section in the "Base" we replace.
703 old_size: u8,
704 /// the size of the new section that get inserted.
705 new_size: u8,
706 }
707
708 impl TestChain {
709 /// turn into a "simplified" expression into a TestChain
710 ///
711 /// The delta_spec express the chain as slice de delta, each expressed
712 /// as a slice of three item tuple: (pos, old_size, new_size)
713 ///
714 /// The actual bytes used for the full text and delta are automatically
715 /// computed (see [`TestChain`] for details).
716 fn new(
717 initial_size: usize,
718 deltas_spec: &[&[(usize, usize, usize)]],
719 ) -> Self {
720 assert!(MIN_SIZE <= initial_size);
721 assert!(initial_size <= MAX_SIZE);
722 let mut deltas = vec![];
723 let mut src_size = initial_size as u8;
724 for d_spec in deltas_spec.iter() {
725 let mut new_size: i8 = src_size as i8;
726 let mut pieces = vec![];
727 for (pos, old, new) in d_spec.iter() {
728 new_size += *new as i8;
729 new_size -= *old as i8;
730 pieces.push(TestPiece {
731 pos: *pos as u8,
732 old_size: *old as u8,
733 new_size: *new as u8,
734 })
735 }
736 deltas.push(TestDelta {
737 src_size,
738 dst_size: new_size as u8,
739 pieces,
740 });
741 src_size = new_size as u8;
742 }
743 Self { initial_size: initial_size as u8, deltas }
744 }
745
746 fn random(seed: u64) -> Self {
747 let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
748 let mut src_size = (rng.random::<u8>() % 9u8) + 1u8;
749 let mut chain =
750 TestChain { initial_size: src_size, deltas: vec![] };
751 for _ in 1..(rng.random::<u8>() % 24) + 1u8 {
752 let size_change = (rng.random::<u8>() % 7) as i8 - 3;
753 let next_size = ((src_size as i8) + size_change)
754 .max(MIN_SIZE as i8)
755 .min(MAX_SIZE as i8) as u8;
756 let size_change = next_size as i8 - src_size as i8;
757 assert!(next_size <= 10);
758 assert!(1 <= next_size);
759
760 let mut d = TestDelta {
761 src_size: src_size,
762 dst_size: next_size,
763 pieces: vec![],
764 };
765
766 let max_pos = src_size + 1;
767 let nb_pick = rng.random_range(1..10);
768 let mut selected_pos = std::collections::HashSet::new();
769 for _ in 0..nb_pick {
770 let picked = rng.random_range(0..max_pos);
771 selected_pos.insert(picked);
772 }
773 let mut used_pos: Vec<u8> = selected_pos.into_iter().collect();
774 used_pos.sort();
775 used_pos.reverse();
776
777 let mut tmp_patches = vec![];
778 let mut current_size_change: i8 = 0;
779
780 while let Some(start) = used_pos.pop() {
781 // select the end of the range
782 let end = if rng.random::<bool>() {
783 used_pos.pop().unwrap_or(start)
784 } else {
785 start
786 };
787 assert!(start <= end, "{} <= {}", start, end);
788 let old_size = end - start;
789 let new_size = if start == end { 1 } else { 0 };
790 current_size_change += new_size as i8 - old_size as i8;
791 assert!(start <= d.src_size);
792 assert!(start + old_size <= d.src_size);
793 tmp_patches.push(TestPiece {
794 pos: start,
795 old_size,
796 new_size,
797 });
798 }
799
800 tmp_patches.shuffle(&mut rng);
801
802 let mut change_budget = size_change - current_size_change;
803
804 if change_budget >= 0 {
805 for p in tmp_patches.iter_mut() {
806 if change_budget > 0 {
807 let extra: i8 = rng.random_range(0..change_budget);
808 p.new_size += extra as u8;
809 change_budget -= extra;
810 }
811 }
812 } else {
813 tmp_patches = tmp_patches
814 .into_iter()
815 .filter(|p| {
816 if p.old_size > 0 {
817 true
818 } else {
819 if change_budget >= 0 {
820 true
821 } else {
822 change_budget += p.new_size as i8;
823 false
824 }
825 }
826 })
827 .collect();
828 if tmp_patches.is_empty() {
829 if change_budget <= -(src_size as i8) {
830 change_budget = -(src_size as i8) + 1
831 }
832 let max_pos =
833 (src_size as i8 + change_budget.min(-1)) as u8;
834 let pos = rng.random_range(0..max_pos + 1);
835 tmp_patches.push(if change_budget >= 0 {
836 TestPiece { pos, old_size: 1, new_size: 1 }
837 } else {
838 TestPiece {
839 pos,
840 old_size: (-change_budget as u8),
841 new_size: 0,
842 }
843 });
844 }
845 if change_budget < 0 {
846 change_budget = 0;
847 d.dst_size = (d.dst_size as i8 - change_budget) as u8;
848 }
849 }
850
851 assert!(!tmp_patches.is_empty());
852 tmp_patches.sort_by(|a, b| a.pos.cmp(&b.pos));
853 for p in tmp_patches.into_iter() {
854 d.pieces.push(p);
855 }
856 assert!(!d.pieces.is_empty());
857 if change_budget > 0 {
858 let p: &mut TestPiece =
859 (&mut d.pieces[..]).choose_mut(&mut rng).unwrap();
860 p.new_size += change_budget as u8;
861 change_budget = 0
862 }
863 assert_eq!(change_budget, 0);
864 src_size = d.dst_size;
865 assert!(src_size <= 10, "{}", src_size);
866 assert!(1 <= src_size, "{}", src_size);
867 chain.deltas.push(d);
868 }
869 chain
870 }
871 fn full_text(&self) -> Vec<u8> {
872 assert!(self.initial_size <= 10);
873 let mut text = vec![];
874 for i in 0..self.initial_size {
875 text.push(i as u8);
876 }
877 text
878 }
879
880 /// Return all deltas in their binary serialization
881 fn deltas(&self) -> Vec<Vec<u8>> {
882 let mut pieces = vec![];
883 for (idx, d) in self.deltas.iter().enumerate() {
884 let mut data = PatchDataBuilder::new();
885 let idx = (idx + 1) as u8;
886 let new_data = [
887 (idx * 10) + 0,
888 (idx * 10) + 1,
889 (idx * 10) + 2,
890 (idx * 10) + 3,
891 (idx * 10) + 4,
892 (idx * 10) + 5,
893 (idx * 10) + 6,
894 (idx * 10) + 7,
895 (idx * 10) + 8,
896 (idx * 10) + 9,
897 ];
898 let mut cursor: usize = 0;
899 for p in &d.pieces {
900 let start = p.pos;
901 let end = p.pos + p.old_size;
902 let cursor_end = cursor + p.new_size as usize;
903 assert!(cursor_end <= 10);
904 let new = &new_data[cursor..cursor_end];
905 data.replace(start as usize, end as usize, new);
906 cursor = cursor_end;
907 }
908 pieces.push(data.data);
909 }
910 pieces
911 }
912
913 /// return the expected final Full-Text from applying this delta Chain
914 fn expected(&self) -> Vec<u8> {
915 let mut content = self.full_text();
916 for d in self.deltas() {
917 let patch = Delta::new(&d).unwrap();
918 let mut buffer = CoreRevisionBuffer::new();
919 patch.apply(&mut buffer, &content);
920 content = buffer.finish();
921 }
922 content
923 }
924
925 /// return a copy of this TestChain without the tip most patch.
926 fn sub_chain(&self) -> Self {
927 let mut other = self.clone();
928 other.deltas.pop();
929 other
930 }
931
932 /// return the result of apply this chain
933 ///
934 /// (using the iterator approach)
935 fn apply_result(&self) -> Vec<u8> {
936 let full_text = self.full_text();
937 let deltas = self.deltas();
938 apply_chain(&full_text, &deltas, self.final_size()).unwrap()
939 }
940
941 fn eprint(&self) {
942 eprintln!("TestChain [");
943 eprintln!(" base {}", self.initial_size);
944 for d in &self.deltas {
945 eprintln!(" delta {} -> {}", d.src_size, d.dst_size);
946 for p in &d.pieces {
947 eprintln!(
948 " # {} -{} +{} ~> {}",
949 p.pos,
950 p.old_size,
951 p.new_size,
952 p.new_size as i8 - p.old_size as i8,
953 )
954 }
955 }
956 eprintln!("]");
957 }
958
959 /// the expected size of final content
960 fn final_size(&self) -> u32 {
961 match &self.deltas[..] {
962 [] => self.initial_size,
963 [.., last] => last.dst_size,
964 }
965 .into()
966 }
967 }
968
969 impl Ord for TestChain {
970 /// simpler chain are "smaller" than the more complex one
971 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
972 if self.deltas.len() != other.deltas.len() {
973 self.deltas.len().cmp(&other.deltas.len())
974 } else {
975 let local_patch_count: usize =
976 self.deltas.iter().map(|d| d.pieces.len()).sum();
977 let other_patch_count: usize =
978 other.deltas.iter().map(|d| d.pieces.len()).sum();
979 local_patch_count.cmp(&other_patch_count)
980 }
981 }
982 }
983
984 struct PatchDataBuilder {
985 data: Vec<u8>,
986 }
987
988 impl PatchDataBuilder {
989 pub fn new() -> Self {
990 Self { data: vec![] }
991 }
992
993 pub fn replace(
994 &mut self,
995 start: usize,
996 end: usize,
997 data: &[u8],
998 ) -> &mut Self {
999 assert!(start <= end);
1000 self.data.extend(&(start as i32).to_be_bytes());
1001 self.data.extend(&(end as i32).to_be_bytes());
1002 self.data.extend(&(data.len() as i32).to_be_bytes());
1003 self.data.extend(data.iter());
1004 self
1005 }
1006 }
1007
1008 #[test]
1009 fn test_ends_before() {
1010 let chain = TestChain::new(3, &[&[(0, 1, 2)], &[(2, 2, 3)]]);
1011
1012 // test that the testing tool generated what we want
1013 //
1014 // This is a way to sanity check the testing tool.
1015 let expected = chain.expected();
1016 assert_eq!(expected, vec![10u8, 11, 20, 21, 22]);
1017
1018 let result = chain.apply_result();
1019 assert_eq!(result, expected);
1020 }
1021
1022 #[test]
1023 fn test_starts_after() {
1024 let chain = TestChain::new(3, &[&[(0, 1, 1)], &[(1, 1, 2)]]);
1025
1026 // test that the testing tool generated what we want
1027 //
1028 // This is a way to sanity check the testing tool.
1029 let expected = chain.expected();
1030 assert_eq!(expected, vec![10u8, 20, 21, 2]);
1031
1032 let result = chain.apply_result();
1033 assert_eq!(result, expected);
1034 }
1035
1036 #[test]
1037 fn test_overridden() {
1038 let chain = TestChain::new(3, &[&[(1, 1, 2)], &[(1, 3, 3)]]);
1039
1040 // test that the testing tool generated what we want
1041 //
1042 // This is a way to sanity check the testing tool.
1043 let expected = chain.expected();
1044 assert_eq!(expected, vec![0u8, 20, 21, 22]);
1045
1046 let result = chain.apply_result();
1047 assert_eq!(result, expected);
1048 }
1049
1050 #[test]
1051 fn test_right_most_part_is_overridden() {
1052 let chain = TestChain::new(3, &[&[(0, 1, 2)], &[(1, 3, 3)]]);
1053
1054 // test that the testing tool generated what we want
1055 //
1056 // This is a way to sanity check the testing tool.
1057 let expected = chain.expected();
1058 assert_eq!(expected, vec![10u8, 20, 21, 22]);
1059
1060 let result = chain.apply_result();
1061 assert_eq!(result, expected);
1062 }
1063
1064 #[test]
1065 fn test_left_most_part_is_overridden() {
1066 let chain = TestChain::new(3, &[&[(1, 2, 3)], &[(0, 2, 2)]]);
1067
1068 // test that the testing tool generated what we want
1069 //
1070 // This is a way to sanity check the testing tool.
1071 let expected = chain.expected();
1072 assert_eq!(expected, vec![20u8, 21, 11, 12]);
1073
1074 let result = chain.apply_result();
1075 assert_eq!(result, expected);
1076 }
1077
1078 #[test]
1079 fn test_mid_is_overridden() {
1080 let chain = TestChain::new(3, &[&[(0, 3, 4)], &[(1, 2, 2)]]);
1081
1082 // test that the testing tool generated what we want
1083 //
1084 // This is a way to sanity check the testing tool.
1085 let expected = chain.expected();
1086 assert_eq!(expected, vec![10u8, 20, 21, 13]);
1087
1088 let result = chain.apply_result();
1089 assert_eq!(result, expected);
1090 }
1091
1092 #[test]
1093 fn test_simple_interleaved() {
1094 let chain = TestChain::new(3, &[&[(1, 1, 2), (3, 0, 1)]]);
1095
1096 // test that the testing tool generated what we want
1097 //
1098 // This is a way to sanity check the testing tool.
1099 let expected = chain.expected();
1100 assert_eq!(expected, vec![0u8, 10, 11, 2, 12]);
1101
1102 let result = chain.apply_result();
1103 assert_eq!(result, expected);
1104 }
1105
1106 #[test]
1107 fn test_stacking_3_patches() {
1108 let chain = TestChain::new(
1109 3,
1110 &[
1111 &[(1, 1, 2), (3, 0, 1)],
1112 &[(0, 2, 0), (3, 1, 2)],
1113 &[(0, 0, 1), (1, 1, 2)],
1114 ],
1115 );
1116
1117 // test that the testing tool generated what we want
1118 //
1119 // This is a way to sanity check the testing tool.
1120 let expected = chain.expected();
1121 assert_eq!(expected, vec![30u8, 11, 31, 32, 21, 12]);
1122
1123 let result = chain.apply_result();
1124 assert_eq!(result, expected);
1125 }
1126
1127 const PATCH_COUNT: usize = 18;
1128
1129 #[test]
1130 fn test_append_multiple_time() {
1131 // we don't use the TestChain here because we build content longer than
1132 // 10 bytes
1133 let data = vec![0u8, 1, 2, 3, 4];
1134 let mut expected = vec![];
1135 expected.extend_from_slice(&data);
1136
1137 let mut patch_data = vec![];
1138 for idx in 0..PATCH_COUNT {
1139 let offset = 5 * (1 + idx);
1140 let v = 10u8 * (1 + idx as u8);
1141 let mut p = PatchDataBuilder::new();
1142 let data = [v, v + 1, v + 2, v + 3, v + 4];
1143 p.replace(offset, offset, &data);
1144 patch_data.push(p);
1145 expected.extend_from_slice(&data);
1146 }
1147
1148 let deltas: Vec<_> = patch_data.into_iter().map(|d| d.data).collect();
1149 let result =
1150 apply_chain(&data, &deltas, u_u32(expected.len())).unwrap();
1151 assert_eq!(result, expected);
1152 }
1153
1154 #[test]
1155 fn test_insert_multiple_time() {
1156 // we don't use the TestChain here because we build content longer than
1157 // 10 bytes
1158 let data = vec![0u8, 1, 2, 3, 4];
1159 let mut expected = vec![];
1160 expected.extend_from_slice(&data);
1161
1162 let mut patch_data = vec![];
1163 for idx in 0..PATCH_COUNT {
1164 let v = 10u8 * (1 + idx as u8);
1165 let mut p = PatchDataBuilder::new();
1166 let data = [v, v + 1, v + 2, v + 3, v + 4];
1167 p.replace(0, 0, &data);
1168 patch_data.push(p);
1169 let mut new_expected = vec![];
1170 new_expected.extend_from_slice(&data);
1171 new_expected.extend_from_slice(&expected);
1172 expected = new_expected;
1173 }
1174
1175 let deltas: Vec<_> = patch_data.into_iter().map(|d| d.data).collect();
1176 let result =
1177 apply_chain(&data, &deltas, u_u32(expected.len())).unwrap();
1178 assert_eq!(result, expected);
1179 }
1180
1181 #[test]
1182 fn test_interleaved_append_multiple_time() {
1183 // we don't use the TestChain here because we build content longer than
1184 // 10 bytes
1185 let data = vec![0u8, 1, 2, 3, 4];
1186
1187 let mut expected = vec![];
1188 for n in 0..5 {
1189 for idx in 0..(PATCH_COUNT + 1) {
1190 let v = (n + (10 * idx)) as u8;
1191 expected.push(v);
1192 }
1193 }
1194
1195 let mut patch_data = vec![];
1196 for idx in 1..PATCH_COUNT + 1 {
1197 let mut p = PatchDataBuilder::new();
1198 let block_size = idx;
1199 let v = 10u8 * idx as u8;
1200 for n in 0..5 {
1201 let offset = block_size * (n + 1);
1202 p.replace(offset, offset, &[v + (n as u8)]);
1203 }
1204 patch_data.push(p);
1205 }
1206
1207 let deltas: Vec<_> = patch_data.into_iter().map(|d| d.data).collect();
1208 let result =
1209 apply_chain(&data, &deltas, u_u32(expected.len())).unwrap();
1210 assert_eq!(result, expected);
1211 }
1212
1213 #[test]
1214 fn test_interleaved_insert_multiple_time() {
1215 // we don't use the TestChain here because we build content longer than
1216 // 10 bytes
1217 let data = vec![0u8, 1, 2, 3, 4];
1218
1219 let mut expected = vec![];
1220 for n in 0..5 {
1221 for idx in (0..(PATCH_COUNT + 1)).rev() {
1222 let v = (n + (10 * idx)) as u8;
1223 expected.push(v);
1224 }
1225 }
1226
1227 let mut patch_data = vec![];
1228 for idx in 0..PATCH_COUNT {
1229 let mut p = PatchDataBuilder::new();
1230 let block_size = 1 + idx;
1231 let v = 10u8 * (1 + idx as u8);
1232 for n in 0..5 {
1233 let offset = block_size * n;
1234 p.replace(offset, offset, &[v + (n as u8)]);
1235 }
1236 patch_data.push(p);
1237 }
1238
1239 let deltas: Vec<_> = patch_data.into_iter().map(|d| d.data).collect();
1240 let result =
1241 apply_chain(&data, &deltas, u_u32(expected.len())).unwrap();
1242 assert_eq!(result, expected);
1243 }
1244
1245 #[test]
1246 /// complexe case reduced from a real life failure
1247 fn test_complex_01() {
1248 // we don't use the TestChain here because we build content longer than
1249 // 10 bytes
1250 let data = vec![0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1251 let mut patch_data = vec![];
1252
1253 // insert 10 more bytes (20 total)
1254 let mut p = PatchDataBuilder::new();
1255 p.replace(5, 5, &[10u8, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
1256 patch_data.push(p);
1257
1258 // empty patch
1259 let p = PatchDataBuilder::new();
1260 patch_data.push(p);
1261
1262 // append 5 more bytes (25 total)
1263 let mut p = PatchDataBuilder::new();
1264 p.replace(20, 20, &[20u8, 21, 22, 23, 24]);
1265 patch_data.push(p);
1266
1267 // insert 5 more bytes (30 total)
1268 let mut p = PatchDataBuilder::new();
1269 p.replace(0, 0, &[30u8, 31, 32, 33, 34]);
1270 patch_data.push(p);
1271
1272 // alter a small section, dropping 2 bytes (28 total)
1273 let mut p = PatchDataBuilder::new();
1274 p.replace(7, 13, &[40u8, 41, 42, 43]);
1275 patch_data.push(p);
1276
1277 // alter the end of this section same amount of bytes (28 total)
1278 let mut p = PatchDataBuilder::new();
1279 p.replace(9, 11, &[50u8, 51]);
1280 patch_data.push(p);
1281
1282 // empty patch
1283 let p = PatchDataBuilder::new();
1284 patch_data.push(p);
1285
1286 // empty patch
1287 let p = PatchDataBuilder::new();
1288 patch_data.push(p);
1289
1290 // insert 5 more bytes somewhere (33 total)
1291 let mut p = PatchDataBuilder::new();
1292 p.replace(12, 12, &[60u8, 61, 62, 63, 64]);
1293 patch_data.push(p);
1294
1295 // alter the same section again (33 total)
1296 let mut p = PatchDataBuilder::new();
1297 p.replace(9, 11, &[70u8, 71]);
1298 patch_data.push(p);
1299
1300 // insert more data (38 total)
1301 let mut p = PatchDataBuilder::new();
1302 p.replace(20, 20, &[80u8, 81, 82, 83, 84]);
1303 patch_data.push(p);
1304
1305 // alter the same section again (38 total)
1306 let mut p = PatchDataBuilder::new();
1307 p.replace(9, 11, &[90u8, 91]);
1308 patch_data.push(p);
1309
1310 // insert more data close to the end (43 total)
1311 let mut p = PatchDataBuilder::new();
1312 p.replace(27, 27, &[100u8, 101, 102, 103, 104]);
1313 patch_data.push(p);
1314
1315 // delete the end (38 total)
1316 let mut p = PatchDataBuilder::new();
1317 p.replace(38, 43, &[]);
1318 patch_data.push(p);
1319
1320 // insert new thing before the end part
1321 let mut p = PatchDataBuilder::new();
1322 p.replace(33, 33, &[110u8, 111, 112, 113, 114]);
1323 patch_data.push(p);
1324
1325 let expected = &[
1326 30u8, 31, 32, 33, 34, 0, 1, 40, 41, 90, 91, 13, 60, 61, 62, 63, 64,
1327 14, 15, 16, 80, 81, 82, 83, 84, 17, 18, 100, 101, 102, 103, 104,
1328 19, 110, 111, 112, 113, 114, 5, 6, 7, 8, 9,
1329 ];
1330
1331 let deltas: Vec<_> = patch_data.into_iter().map(|d| d.data).collect();
1332 let result =
1333 apply_chain(&data, &deltas, u_u32(expected.len())).unwrap();
1334 assert_eq!(result, expected);
1335 }
1336
1337 #[test]
1338 /// from a generated case
1339 fn test_complex_02() {
1340 let chain = TestChain::new(
1341 6,
1342 &[
1343 &[(4, 1, 0), (6, 0, 1)],
1344 &[(1, 4, 7)],
1345 &[(4, 0, 1)],
1346 &[(0, 1, 0)],
1347 &[(2, 0, 3), (7, 1, 0)],
1348 ],
1349 );
1350
1351 let result = chain.apply_result();
1352 let expected = chain.expected();
1353 assert_eq!(result, expected);
1354 }
1355
1356 #[test]
1357 /// from a generated case
1358 fn test_complex_03() {
1359 let chain = TestChain::new(
1360 6,
1361 &[
1362 &[(2, 3, 1), (6, 0, 2)],
1363 &[(4, 1, 0), (6, 0, 1)],
1364 &[(1, 3, 0)],
1365 &[(1, 2, 5)],
1366 &[(1, 4, 7)],
1367 &[(4, 0, 1)],
1368 &[(0, 1, 0)],
1369 &[(2, 0, 3), (7, 1, 0)],
1370 ],
1371 );
1372
1373 let result = chain.apply_result();
1374 let expected = chain.expected();
1375 assert_eq!(result, expected);
1376 }
1377
1378 #[test]
1379 /// from a generated case
1380 fn test_complex_04() {
1381 let chain = TestChain::new(
1382 5,
1383 &[
1384 &[(1, 2, 0)],
1385 &[(0, 3, 1)],
1386 &[(0, 1, 1)],
1387 &[(0, 0, 1), (1, 0, 2)],
1388 &[(0, 2, 0), (3, 0, 5)],
1389 &[(5, 1, 0)],
1390 ],
1391 );
1392
1393 let result = chain.apply_result();
1394 let expected = chain.expected();
1395 assert_eq!(result, expected);
1396 }
1397
1398 #[test]
1399 /// some automatically generated test
1400 ///
1401 /// You should probably use proptest for that, but that is a good start
1402 fn test_generated() {
1403 let mut test_chains = vec![];
1404 for seed in 0..1024 {
1405 test_chains.push(TestChain::random(seed));
1406 }
1407
1408 // try the simplest case first
1409 test_chains.sort();
1410
1411 for chain in test_chains.into_iter() {
1412 let result = chain.apply_result();
1413 let expected = chain.expected();
1414
1415 // if we get a bad result, we shorten it to the smallest chain that
1416 // still fails.
1417 if result != expected {
1418 let mut last_bad_chain = chain.clone();
1419 let mut current_chain = chain.clone();
1420 while !current_chain.deltas.is_empty() {
1421 current_chain = last_bad_chain.sub_chain();
1422 let sub_result = chain.apply_result();
1423 let sub_expected = chain.expected();
1424 if sub_result == sub_expected {
1425 break;
1426 }
1427 last_bad_chain = current_chain.clone();
1428 }
1429 last_bad_chain.eprint();
1430 assert_eq!(
1431 last_bad_chain.apply_result(),
1432 last_bad_chain.expected(),
1433 "{:?}",
1434 last_bad_chain,
1435 );
1436 }
1437 }
1438 }
1439 }