Debian Codegraph @

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

raw
1 use std::cmp::Ordering as O;
2 use std::num::NonZeroU8;
3 use std::ops::Deref;
4
5 use super::diff::lines_prefix_size_low;
6 use super::diff::CMP_BLK_SIZE;
7 use super::patch::DeltaPiece;
8 use super::RevlogType;
9 use crate::errors::HgError;
10 use crate::revlog::diff::DeltaCursor;
11 use crate::revlog::options::RevlogOpenOptions;
12 use crate::revlog::patch;
13 use crate::revlog::Node;
14 use crate::revlog::NodePrefix;
15 use crate::revlog::Revlog;
16 use crate::revlog::RevlogError;
17 use crate::utils::hg_path::HgPath;
18 use crate::utils::strings::SliceExt;
19 use crate::vfs::VfsImpl;
20 use crate::Graph;
21 use crate::GraphError;
22 use crate::Revision;
23 use crate::UncheckedRevision;
24 use crate::NULL_REVISION;
25
26 /// A specialized `Revlog` to work with `manifest` data format.
27 pub struct Manifestlog {
28 /// The generic `revlog` format.
29 pub(crate) revlog: Revlog,
30 }
31
32 impl Graph for Manifestlog {
33 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
34 self.revlog.parents(rev)
35 }
36 }
37
38 impl Manifestlog {
39 /// Open the `manifest` of a repository given by its root.
40 pub fn open(
41 store_vfs: &VfsImpl,
42 options: RevlogOpenOptions,
43 ) -> Result<Self, HgError> {
44 let revlog = Revlog::open(
45 store_vfs,
46 "00manifest.i",
47 None,
48 options,
49 RevlogType::Manifestlog,
50 )?;
51 Ok(Self { revlog })
52 }
53
54 /// Return the `Manifest` for the given node ID.
55 ///
56 /// Note: this is a node ID in the manifestlog, typically found through
57 /// `ChangelogEntry::manifest_node`. It is *not* the node ID of any
58 /// changeset.
59 ///
60 /// See also `Repo::manifest_for_node`
61 pub fn data_for_node(
62 &self,
63 node: NodePrefix,
64 ) -> Result<Manifest, RevlogError> {
65 let rev = self.revlog.rev_from_node(node)?;
66 self.data(rev)
67 }
68
69 /// Return the `Manifest` of a given revision number.
70 ///
71 /// Note: this is a revision number in the manifestlog, *not* of any
72 /// changeset.
73 ///
74 /// See also `Repo::manifest_for_rev`
75 pub fn data_for_unchecked_rev(
76 &self,
77 rev: UncheckedRevision,
78 ) -> Result<Manifest, RevlogError> {
79 let bytes = self.revlog.get_data_for_unchecked_rev(rev)?;
80 Ok(Manifest { bytes: Box::new(bytes) })
81 }
82
83 /// Same as [`Self::data_for_unchecked_rev`] for a checked [`Revision`]
84 pub fn data(&self, rev: Revision) -> Result<Manifest, RevlogError> {
85 let bytes = self.revlog.get_data(rev)?;
86 Ok(Manifest { bytes: Box::new(bytes) })
87 }
88
89 /// Returns a manifest containing entries for `rev` that are not in its
90 /// parents. It is inexact because it might return a superset of this.
91 /// Equivalent to `manifestctx.read_delta_parents(exact=False)` in Python.
92 pub fn inexact_data_delta_parents(
93 &self,
94 rev: Revision,
95 ) -> Result<Manifest, RevlogError> {
96 let delta_parent = self.revlog.delta_parent(rev);
97 let parents = self.parents(rev).map_err(|err| {
98 RevlogError::corrupted(format!("rev {rev}: {err}"))
99 })?;
100 if delta_parent == NULL_REVISION || !parents.contains(&delta_parent) {
101 return self.data(rev);
102 }
103 let mut bytes = vec![];
104 for chunk in self.revlog.get_data_incr(rev)?.as_delta()?.chunks {
105 bytes.extend_from_slice(chunk.data);
106 }
107 Ok(Manifest { bytes: Box::new(bytes) })
108 }
109 }
110
111 /// `Manifestlog` entry which knows how to interpret the `manifest` data bytes.
112 pub struct Manifest {
113 /// Format for a manifest: flat sequence of variable-size entries,
114 /// sorted by path, each as:
115 ///
116 /// ```text
117 /// <path> \0 <hex_node_id> <flags> \n
118 /// ```
119 ///
120 /// The last entry is also terminated by a newline character.
121 /// Flags is one of `b""` (the empty string), `b"x"`, `b"l"`, or `b"t"`.
122 bytes: Box<dyn Deref<Target = [u8]> + Send + Sync>,
123 }
124
125 impl Manifest {
126 /// Return a new empty manifest
127 pub fn empty() -> Self {
128 Self { bytes: Box::new(vec![]) }
129 }
130
131 pub fn from_bytes(
132 bytes: Box<dyn Deref<Target = [u8]> + Send + Sync>,
133 ) -> Self {
134 Self { bytes }
135 }
136
137 pub fn iter(&self) -> impl Iterator<Item = Result<ManifestEntry, HgError>> {
138 self.bytes
139 .split(|b| b == &b'\n')
140 .filter(|line| !line.is_empty())
141 .map(ManifestEntry::from_raw)
142 }
143
144 /// If the given path is in this manifest, return its filelog node ID
145 pub fn find_by_path(
146 &self,
147 path: &HgPath,
148 ) -> Result<Option<ManifestEntry>, HgError> {
149 use std::cmp::Ordering::*;
150 let path = path.as_bytes();
151 // Both boundaries of this `&[u8]` slice are always at the boundary of
152 // an entry
153 let mut bytes: &[u8] = &self.bytes;
154
155 // Binary search algorithm derived from `[T]::binary_search_by`
156 // <https://github.com/rust-lang/rust/blob/1.57.0/library/core/src/slice/mod.rs#L2221>
157 // except we don’t have a slice of entries. Instead we jump to the
158 // middle of the byte slice and look around for entry delimiters
159 // (newlines).
160 while let Some(entry_range) = Self::find_entry_near_middle_of(bytes)? {
161 let (entry_path, rest) =
162 ManifestEntry::split_path(&bytes[entry_range.clone()])?;
163 let cmp = entry_path.cmp(path);
164 if cmp == Less {
165 let after_newline = entry_range.end + 1;
166 bytes = &bytes[after_newline..];
167 } else if cmp == Greater {
168 bytes = &bytes[..entry_range.start];
169 } else {
170 return Ok(Some(ManifestEntry::from_path_and_rest(
171 entry_path, rest,
172 )));
173 }
174 }
175 Ok(None)
176 }
177
178 /// If there is at least one, return the byte range of an entry *excluding*
179 /// the final newline.
180 fn find_entry_near_middle_of(
181 bytes: &[u8],
182 ) -> Result<Option<std::ops::Range<usize>>, HgError> {
183 let len = bytes.len();
184 if len > 0 {
185 let middle = bytes.len() / 2;
186 // Integer division rounds down, so `middle < len`.
187 let (before, after) = bytes.split_at(middle);
188 let entry_start = match memchr::memrchr(b'\n', before) {
189 Some(i) => i + 1,
190 None => 0, // We choose the first entry in `bytes`
191 };
192 let entry_end = match memchr::memchr(b'\n', after) {
193 Some(i) => {
194 // No `+ 1` here to exclude this newline from the range
195 middle + i
196 }
197 None => {
198 // In a well-formed manifest:
199 //
200 // * Since `len > 0`, `bytes` contains at least one entry
201 // * Every entry ends with a newline
202 // * Since `middle < len`, `after` contains at least the
203 // newline at the end of the last entry of `bytes`.
204 //
205 // We didn’t find a newline, so this manifest is not
206 // well-formed.
207 return Err(HgError::corrupted(
208 "manifest entry without \\n delimiter",
209 ));
210 }
211 };
212 Ok(Some(entry_start..entry_end))
213 } else {
214 // len == 0
215 Ok(None)
216 }
217 }
218
219 #[tracing::instrument(level = "trace", skip_all)]
220 pub fn diff<'m1: 'm_any, 'm2: 'm_any, 'm_any>(
221 &'m1 self,
222 other: &'m2 Manifest,
223 ) -> Result<ManifestDiff<'m_any>, HgError> {
224 let mut res = Vec::new();
225 for lines in SyncLineIterator::new(&self.bytes, &other.bytes) {
226 match lines {
227 (Some(l), None) => res.push((Some(l.into_entry()?), None)),
228 (None, Some(l)) => res.push((None, Some(l.into_entry()?))),
229 (Some(l1), Some(l2)) => {
230 if l1.data() != l2.data() {
231 res.push((
232 Some(l1.into_entry()?),
233 Some(l2.into_entry()?),
234 ))
235 }
236 }
237 (None, None) => unreachable!(
238 "iteration continue despite no remaining lines."
239 ),
240 };
241 }
242
243 Ok(res)
244 }
245 }
246
247 pub type ManifestDiff<'a> =
248 Vec<(Option<ManifestEntry<'a>>, Option<ManifestEntry<'a>>)>;
249
250 /// Represents the flags of a given [`ManifestEntry`].
251 #[derive(Copy, Clone, Debug, PartialEq)]
252 pub struct ManifestFlags(Option<NonZeroU8>);
253
254 impl ManifestFlags {
255 pub fn new_empty() -> Self {
256 Self(None)
257 }
258
259 pub fn new_link() -> Self {
260 Self(Some(b'l'.try_into().unwrap()))
261 }
262
263 pub fn new_exec() -> Self {
264 Self(Some(b'x'.try_into().unwrap()))
265 }
266
267 pub fn new_tree() -> Self {
268 Self(Some(b't'.try_into().unwrap()))
269 }
270
271 /// Whether this path is a symlink
272 pub fn is_link(&self) -> bool {
273 self.is_flag(b'l')
274 }
275
276 /// Whether this path has the executable permission set
277 pub fn is_exec(&self) -> bool {
278 self.is_flag(b'x')
279 }
280
281 /// Whether this path is a tree in the context of treemanifest
282 pub fn is_tree(&self) -> bool {
283 self.is_flag(b't')
284 }
285
286 fn is_flag(&self, flag: u8) -> bool {
287 self.0.map(|f| f == NonZeroU8::new(flag).unwrap()).unwrap_or(false)
288 }
289 }
290
291 /// A manifest line is a Lazy ManifestEntry used during comparison
292 #[derive(Copy, Clone)]
293 struct ManifestLine<'a> {
294 /// The size of that manifest line
295 line: &'a [u8],
296 /// An optional length of the filename in case it was already computed
297 ///
298 /// A value < 0 means the value is not initialized.
299 filename_len: i32,
300 }
301
302 impl<'a> ManifestLine<'a> {
303 /// Grabs the next line from a byte slice and returns the line if any,
304 /// with the remainder of the byte slice
305 fn grab_next(data: &'a [u8]) -> (Option<ManifestLine<'a>>, &'a [u8]) {
306 if !data.is_empty() {
307 match memchr::memchr(b'\n', data) {
308 None => (None, data),
309 Some(pos) => (
310 Some(Self { line: &data[0..pos + 1], filename_len: -1 }),
311 &data[pos + 1..],
312 ),
313 }
314 } else {
315 (None, data)
316 }
317 }
318
319 /// Size of the line in bytes
320 fn size(&self) -> u32 {
321 self.line.len().try_into().expect("manifest line larger than 4GB?")
322 }
323
324 /// The filename part of that line
325 ///
326 /// When accessing this, the `filename_len` is cached to speedup future
327 /// access to the "data" part.
328 fn filename(&mut self) -> &'a [u8] {
329 if self.filename_len < 0 {
330 self.filename_len = match memchr::memchr(b'\0', self.line) {
331 None => 0, // no file name should not happen treat it as empty
332 Some(pos) => pos.try_into().expect("manifest larger than 2GB?"),
333 };
334 }
335 debug_assert!(self.filename_len > 0);
336 &self.line[0..self.filename_len as usize]
337 }
338
339 /// The non-filename part of this manifest line
340 pub(self) fn data(self) -> &'a [u8] {
341 debug_assert!(self.filename_len > 0);
342 &self.line[self.filename_len as usize..self.line.len() - 1]
343 }
344
345 fn into_entry(self) -> Result<ManifestEntry<'a>, HgError> {
346 if self.line.is_empty() {
347 Err(HgError::corrupted("empty manifest line"))
348 } else if self.line[self.line.len() - 1] != b'\n' {
349 Err(HgError::corrupted("manifest line not terminated by '\\n'"))
350 } else if self.filename_len == 0 {
351 if self.line[0] == b'\0' {
352 Err(HgError::corrupted("manifest entry with empty filename"))
353 } else {
354 Err(HgError::corrupted("manifest entry without \\0 delimiter"))
355 }
356 } else if self.filename_len < 0 {
357 ManifestEntry::from_raw(&self.line[..self.line.len() - 1])
358 } else {
359 let path = &self.line[0..self.filename_len as usize];
360 let (_, rest) = self
361 .data()
362 .split_first()
363 .expect("previously seen \\0 has vanished");
364 Ok(ManifestEntry::from_path_and_rest(path, rest))
365 }
366 }
367 }
368
369 /// Iterate over two manifests and yield the pair of line associated with each
370 /// filename.
371 ///
372 /// If the manifest are not sorted, this is expected to misbehave
373 struct SyncLineIterator<'a> {
374 m1_data: &'a [u8],
375 m1_line: Option<ManifestLine<'a>>,
376 m2_data: &'a [u8],
377 m2_line: Option<ManifestLine<'a>>,
378 }
379
380 impl<'a> SyncLineIterator<'a> {
381 fn new(m1: &'a [u8], m2: &'a [u8]) -> Self {
382 let (m1_line, m1_data) = ManifestLine::grab_next(m1);
383 let (m2_line, m2_data) = ManifestLine::grab_next(m2);
384 Self { m1_data, m1_line, m2_data, m2_line }
385 }
386 }
387
388 impl<'a> Iterator for SyncLineIterator<'a> {
389 type Item = (Option<ManifestLine<'a>>, Option<ManifestLine<'a>>);
390
391 fn next(&mut self) -> Option<Self::Item> {
392 let result = match (&mut self.m1_line, &mut self.m2_line) {
393 (None, None) => (None, None),
394 (Some(line), None) => (Some(*line), None),
395 (None, Some(line)) => (None, Some(*line)),
396 (Some(l1), Some(l2)) => match l1.filename().cmp(l2.filename()) {
397 std::cmp::Ordering::Less => (Some(*l1), None),
398 std::cmp::Ordering::Equal => (Some(*l1), Some(*l2)),
399 std::cmp::Ordering::Greater => (None, Some(*l2)),
400 },
401 };
402 if result.0.is_some() {
403 (self.m1_line, self.m1_data) =
404 ManifestLine::grab_next(self.m1_data);
405 }
406 if result.1.is_some() {
407 (self.m2_line, self.m2_data) =
408 ManifestLine::grab_next(self.m2_data);
409 }
410 match result {
411 (None, None) => None,
412 r => Some(r),
413 }
414 }
415 }
416
417 /// Result of binary diffing some part of two manifests
418 enum Section {
419 /// Content is the same on both side (size of both)
420 Same(u32),
421 /// Content is different on each side, (size of m1, size of m2)
422 Changed(u32, u32),
423 }
424
425 /// detect the section that are similar or different in two manifest we compare
426 fn changed_sections<'a>(
427 m1: &'a [u8],
428 m2: &'a [u8],
429 ) -> impl Iterator<Item = Section> + 'a {
430 let mut m1 = m1;
431 let mut m2 = m2;
432 let mut same_streak = 0;
433
434 let mut current_iter = None;
435
436 std::iter::from_fn(move || {
437 match (m1, m2) {
438 ([], []) => return None,
439 (tail, []) => {
440 let size = tail.len();
441 m1 = &m1[size..];
442 debug_assert!(m1.is_empty());
443 debug_assert!(m2.is_empty());
444 return Some(Section::Changed(
445 size.try_into().expect("patch data bigger than 2GB"),
446 0,
447 ));
448 }
449 ([], tail) => {
450 let size = tail.len();
451 m2 = &m2[size..];
452 debug_assert!(m1.is_empty());
453 debug_assert!(m2.is_empty());
454 return Some(Section::Changed(
455 0,
456 size.try_into().expect("patch data bigger than 2GB"),
457 ));
458 }
459 (_, _) => (),
460 }
461 // if we have seen enough "same" content from the iterator, lets try
462 // some SIMD comparison first
463 if same_streak > CMP_BLK_SIZE {
464 current_iter.take();
465 }
466 if current_iter.is_none() {
467 let size = lines_prefix_size_low(m1, m2);
468 if size > 0 {
469 m1 = &m1[size..];
470 m2 = &m2[size..];
471 }
472 // we always create an iterator from there as we should not run
473 // prefix matching again until the difference have been
474 // processed
475 current_iter = Some(SyncLineIterator::new(m1, m2));
476 same_streak = 0;
477 if size > 0 {
478 return Some(Section::Same(size as u32));
479 }
480 }
481 Some(
482 match current_iter
483 .as_mut()
484 .expect("programming error, iterator missing")
485 .next()
486 .expect("attempted iteration on empty manifest")
487 {
488 (Some(l), None) => {
489 let size = l.size();
490 m1 = &m1[size as usize..];
491 Section::Changed(size, 0)
492 }
493 (None, Some(l)) => {
494 let size = l.size();
495 m2 = &m2[size as usize..];
496 Section::Changed(0, size)
497 }
498 (Some(l1), Some(l2)) => {
499 let l1_size = l1.size();
500 let l2_size = l2.size();
501 m1 = &m1[l1_size as usize..];
502 m2 = &m2[l2_size as usize..];
503 if l1.data() == l2.data() {
504 same_streak += l1_size as usize;
505 debug_assert!(l1_size == l2_size);
506 Section::Same(l1_size)
507 } else {
508 Section::Changed(l1_size, l2_size)
509 }
510 }
511 (None, None) => unreachable!(
512 "iteration continue despite no remaining lines."
513 ),
514 },
515 )
516 })
517 }
518
519 /// Compute a binary delta between two flat manifest texts
520 pub fn manifest_delta(m1: &[u8], m2: &[u8]) -> Vec<u8> {
521 manifest_delta_with_offset(0, m1, m2)
522 }
523
524 pub(super) fn manifest_delta_with_offset(
525 offset: u32,
526 m1: &[u8],
527 m2: &[u8],
528 ) -> Vec<u8> {
529 let mut delta = vec![];
530 write_manifest_delta_with_offset(offset, m1, m2, &mut delta);
531 delta
532 }
533
534 pub(super) fn write_manifest_delta_with_offset(
535 offset: u32,
536 m1: &[u8],
537 m2: &[u8],
538 delta: &mut Vec<u8>,
539 ) {
540 // our current work position in the two manifest
541 let mut m1_offset = offset;
542 let mut m2_offset = 0u32;
543
544 let mut cursor: Option<DeltaCursor> = None;
545
546 for section in changed_sections(m1, m2) {
547 match section {
548 Section::Same(size) => {
549 m1_offset += size;
550 m2_offset += size;
551 // We have a common block so any existing cursor need flushing
552 if let Some(change) = cursor.take() {
553 change.into_piece().write(delta);
554 }
555 }
556 Section::Changed(size_1, size_2) => {
557 // If a hunk is still around, we must be able to merge with it.
558 if let Some(c) = cursor.as_mut() {
559 c.extend(size_1, size_2)
560 } else {
561 cursor = Some(DeltaCursor::new(
562 m1_offset,
563 m1_offset + size_1,
564 m2_offset,
565 m2_offset + size_2,
566 m2,
567 ));
568 }
569 m1_offset += size_1;
570 m2_offset += size_2;
571 }
572 }
573 }
574 if let Some(change) = cursor.take() {
575 change.into_piece().write(delta);
576 };
577 }
578
579 struct ManifestSection<'a> {
580 chunks: Vec<&'a [u8]>,
581 size: u32,
582 buffer: Vec<u8>,
583 }
584
585 impl<'a> ManifestSection<'a> {
586 fn new() -> Self {
587 Self { chunks: vec![], size: 0, buffer: vec![] }
588 }
589
590 fn push(&mut self, chunk: &'a [u8]) {
591 self.size += chunk.len() as u32;
592 self.chunks.push(chunk);
593 }
594
595 fn clear(&mut self) {
596 self.size = 0;
597 self.chunks.clear();
598 self.buffer.clear();
599 }
600
601 fn is_empty(&self) -> bool {
602 self.size == 0
603 }
604
605 /// write the delta between these two manifest section in `delta`
606 ///
607 /// - `self` is a section of the "old" manifest
608 /// - `other` is a section of the "new" manifest
609 ///
610 /// The patches are created with a `offset`… offset
611 ///
612 /// return the number of `bytes` in "old", to adjust the offset in the
613 /// caller.
614 fn flush_delta(
615 &mut self,
616 other: &mut Self,
617 offset: usize,
618 delta: &mut Vec<u8>,
619 ) -> usize {
620 let offset = offset as u32;
621 let extra_offset = self.size as usize;
622 match (&self.chunks[..], &other.chunks[..]) {
623 ([], []) => return 0,
624 (_, []) => {
625 // the old section is deleted
626 patch::PlainDeltaPiece {
627 start: offset,
628 end: (offset + self.size),
629 data: &[],
630 }
631 .write(delta);
632 }
633 ([], new) => {
634 // the new content is inserted
635 delta.extend_from_slice(&u32::to_be_bytes(offset));
636 delta.extend_from_slice(&u32::to_be_bytes(offset));
637 delta.extend_from_slice(&u32::to_be_bytes(other.size));
638 for c in new {
639 delta.extend_from_slice(c);
640 }
641 }
642 (old, new) => {
643 assert!(self.buffer.is_empty());
644 assert!(other.buffer.is_empty());
645 self.buffer.reserve(self.size as usize);
646 for c in old {
647 self.buffer.extend_from_slice(c);
648 }
649 other.buffer.reserve(other.size as usize);
650 for c in new {
651 other.buffer.extend_from_slice(c);
652 }
653 write_manifest_delta_with_offset(
654 offset,
655 &self.buffer,
656 &other.buffer,
657 delta,
658 );
659 }
660 }
661 self.clear();
662 other.clear();
663 assert!(self.is_empty());
664 assert!(other.is_empty());
665 extra_offset
666 }
667 }
668
669 /// A section of Manifest yield by [`sync_iter`]
670 enum SyncSection<'a> {
671 /// bytes only on the Old content
672 Old(&'a [u8]),
673 /// bytes that are the same on both size
674 Identical(usize),
675 /// bytes only in the New content
676 New(&'a [u8]),
677 /// bytes that exist on both side with some overlapping part
678 Overlapping(&'a [u8], &'a [u8]),
679 }
680
681 fn first_filename(section: &[u8]) -> &[u8] {
682 match memchr::memchr(b'\0', section) {
683 Some(i) => &section[..i],
684 None => {
685 panic!("not a manifest line")
686 }
687 }
688 }
689
690 fn last_filename(section: &[u8]) -> &[u8] {
691 let file_end =
692 memchr::memrchr(b'\0', section).expect("not a manifest line");
693 match memchr::memchr(b'\r', &section[..file_end]) {
694 Some(i) => &section[i..file_end],
695 None => &section[..file_end],
696 }
697 }
698
699 /// Iterate over two series of RichDeltaPiece and yield associate SyncSection
700 ///
701 /// the iteration keep data mostly in sync so that common data can be detected
702 /// and yielded as [`SyncSection::Identical`]
703 fn sync_iter<'a, P>(
704 old_iter: P,
705 new_iter: P,
706 ) -> impl Iterator<Item = SyncSection<'a>>
707 where
708 P: Iterator<Item = patch::RichDeltaPiece<'a>>,
709 {
710 use SyncSection as S;
711
712 let mut old_iter = old_iter.filter(|r| r.size() > 0);
713 let mut new_iter = new_iter.filter(|r| r.size() > 0);
714 let mut current_old = old_iter.next();
715 let mut current_new = new_iter.next();
716 std::iter::from_fn(move || {
717 match (&mut current_old, &mut current_new) {
718 (None, None) => None,
719 (Some(old), None) => {
720 let r = S::Old(old.data());
721 current_old = old_iter.next();
722 Some(r)
723 }
724 (None, Some(new)) => {
725 let r = S::New(new.data());
726 current_new = new_iter.next();
727 Some(r)
728 }
729 (Some(old), Some(new)) => {
730 let r = if old.src == new.src {
731 if old.data_end() <= new.data_start() {
732 // old fully prior to new
733 let r = S::Old(old.data());
734 current_old = old_iter.next();
735 r
736 } else if new.data_end() <= old.data_start() {
737 // new fully prior to old
738 let r = S::New(new.data());
739 current_new = new_iter.next();
740 r
741 } else {
742 // there are some overlap
743 match (
744 old.data_start().cmp(&new.data_start()),
745 old.data_end().cmp(&new.data_end()),
746 ) {
747 (O::Equal, O::Equal) => {
748 // both section as identical, return them both
749 let common_size = old.size();
750 assert_eq!(old.size(), common_size);
751 assert_eq!(new.size(), common_size);
752 let r = S::Identical(common_size as usize);
753 current_old = old_iter.next();
754 current_new = new_iter.next();
755 r
756 }
757 (O::Equal, O::Less) => {
758 // Old is an identical prefix of New
759 // return the identical section and trim New
760 let common_size = old.size();
761 let r = S::Identical(common_size as usize);
762 new.trim_prefix(common_size);
763 assert!(new.data_start() <= new.data_end());
764 current_old = old_iter.next();
765 assert!(!new.is_empty());
766 r
767 }
768 (O::Equal, O::Greater) => {
769 // New is an identical prefix of Old
770 // return the identical section and trim Old
771 let common_size = new.size();
772 let r = S::Identical(common_size as usize);
773 old.trim_prefix(common_size);
774 assert!(old.data_start() <= old.data_end());
775 current_new = new_iter.next();
776 assert!(!old.is_empty());
777 r
778 }
779 (O::Less, _) => {
780 // Old as a unique prefix, return it and trim
781 // Old
782 let prefix =
783 new.data_start() - old.data_start();
784 let r = S::Old(&old.data()[..prefix as usize]);
785 old.trim_prefix(prefix);
786 assert!(!old.is_empty());
787 r
788 }
789 (O::Greater, _) => {
790 // new as a unique prefix, return it and trim
791 // New
792 let prefix =
793 old.data_start() - new.data_start();
794 let r = S::New(&new.data()[..prefix as usize]);
795 new.trim_prefix(prefix);
796 assert!(!new.is_empty());
797 r
798 }
799 }
800 }
801 } else {
802 // iterate things in order to open the opportunity for the
803 // identical section to line up.
804 assert!(!new.is_empty());
805 assert!(!old.is_empty());
806 let old_data = old.data();
807 let new_data = new.data();
808 let last_old = last_filename(old_data);
809 let first_new = first_filename(new_data);
810 if last_old < first_new {
811 let r = S::Old(old_data);
812 current_old = old_iter.next();
813 r
814 } else {
815 let first_old = first_filename(old_data);
816 let last_new = last_filename(new_data);
817 if first_old > last_new {
818 let r = S::New(new_data);
819 current_new = new_iter.next();
820 r
821 } else {
822 match last_old.cmp(last_new) {
823 O::Greater => {
824 // New finish before Old
825 //
826 // The next New might have a common part
827 // with current Old,
828 // flush just New
829 let r = S::New(new_data);
830 current_new = new_iter.next();
831 r
832 }
833 O::Less => {
834 // Old finish before New
835 //
836 // The next Old might have a common part
837 // with current New,
838 // flush just Old
839 let r = S::Old(old_data);
840 current_old = old_iter.next();
841 r
842 }
843 O::Equal => {
844 let r = S::Overlapping(old_data, new_data);
845 current_old = old_iter.next();
846 current_new = new_iter.next();
847 r
848 }
849 }
850 }
851 }
852 };
853 Some(r)
854 }
855 }
856 })
857 }
858
859 pub(super) fn manifest_delta_from_patches<'a, P>(
860 old_iter: P,
861 new_iter: P,
862 ) -> Vec<u8>
863 where
864 P: Iterator<Item = patch::RichDeltaPiece<'a>>,
865 {
866 use SyncSection as S;
867 let mut delta = vec![];
868 let mut old_offset = 0;
869 let mut old_buffer = ManifestSection::new();
870 let mut new_buffer = ManifestSection::new();
871 for section in sync_iter(old_iter, new_iter) {
872 match section {
873 S::Old(data) => old_buffer.push(data),
874 S::New(data) => new_buffer.push(data),
875 S::Overlapping(old, new) => {
876 old_buffer.push(old);
877 new_buffer.push(new);
878 }
879 S::Identical(offset) => {
880 old_offset += old_buffer.flush_delta(
881 &mut new_buffer,
882 old_offset,
883 &mut delta,
884 );
885 old_offset += offset;
886 }
887 }
888 }
889 // flush any potential remains
890 old_buffer.flush_delta(&mut new_buffer, old_offset, &mut delta);
891 delta
892 }
893
894 /// `Manifestlog` entry which knows how to interpret the `manifest` data bytes.
895 #[derive(PartialEq)]
896 pub struct ManifestEntry<'manifest> {
897 pub path: &'manifest HgPath,
898 pub hex_node_id: &'manifest [u8],
899 pub flags: ManifestFlags,
900 }
901
902 impl std::fmt::Debug for ManifestEntry<'_> {
903 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
904 write!(
905 f,
906 "ManifestEntry({:x}:{:?}:'{}')",
907 self.node_id().unwrap(),
908 &self.flags,
909 self.path,
910 )
911 }
912 }
913
914 impl<'a> ManifestEntry<'a> {
915 fn split_path(bytes: &[u8]) -> Result<(&[u8], &[u8]), HgError> {
916 bytes.split_2(b'\0').ok_or_else(|| {
917 HgError::corrupted("manifest entry without \\0 delimiter")
918 })
919 }
920
921 fn from_path_and_rest(path: &'a [u8], rest: &'a [u8]) -> Self {
922 let (hex_node_id, flags) = match rest.split_last() {
923 Some((&b'x', rest)) => (rest, Some(b'x')),
924 Some((&b'l', rest)) => (rest, Some(b'l')),
925 Some((&b't', rest)) => (rest, Some(b't')),
926 _ => (rest, None),
927 };
928 Self {
929 path: HgPath::new(path),
930 hex_node_id,
931 flags: ManifestFlags(
932 flags.map(|f| f.try_into().expect("invalid flag")),
933 ),
934 }
935 }
936
937 fn from_raw(bytes: &'a [u8]) -> Result<Self, HgError> {
938 let (path, rest) = Self::split_path(bytes)?;
939 Ok(Self::from_path_and_rest(path, rest))
940 }
941
942 pub fn node_id(&self) -> Result<Node, HgError> {
943 Node::from_hex_for_repo(self.hex_node_id)
944 }
945 }
946
947 #[cfg(test)]
948 mod tests {
949 use pretty_assertions::assert_eq;
950
951 use super::*;
952 use crate::revlog::inner_revlog::CoreRevisionBuffer;
953 use crate::revlog::inner_revlog::RevisionBuffer;
954 use crate::revlog::patch;
955
956 /// Check that applying the diff from m1 to m2 is the same as m2
957 fn identity_check(m1: &[u8], m2: &[u8], delta: &[u8]) {
958 let mut computed_m2 = CoreRevisionBuffer::new();
959 patch::build_data_from_deltas(&mut computed_m2, m1, &[delta]).unwrap();
960 assert_eq!(
961 String::from_utf8_lossy(&computed_m2.finish()),
962 String::from_utf8_lossy(m2)
963 );
964 }
965
966 fn test_roundtrip(m1: &[u8], m2: &[u8]) {
967 let delta = manifest_delta(m1, m2);
968 identity_check(m1, m2, &delta)
969 }
970
971 #[test]
972 fn test_manifest_diff_simple() {
973 let m1 =
974 b"contrib/perf.py\x001cba44d2ee7e7f148329f51923e71a319168e2e5\n\
975 contrib/phab-clean.py\0e14fa8304bb04039a7e7e7ffa170715fa2136e47x\n";
976 let m2 =
977 b"contrib/perf.py\x001cba44d2ee7e7f148329f51923e71a319168e2e5\n\
978 contrib/phab-clean.py\0e14fa8304bb04039a70ccdcfa170715fa2136e47\n";
979
980 // delete all
981 test_roundtrip(&m1[..], &[]);
982
983 // add all content
984 test_roundtrip(&[], &m1[..]);
985 // identical
986 test_roundtrip(&m1[..], &m1[..]);
987 assert_eq!(manifest_delta(&m1[..], &m1[..]).len(), 0);
988 test_roundtrip(&m2[..], &m2[..]);
989 assert_eq!(manifest_delta(&m2[..], &m2[..]).len(), 0);
990
991 // changing a line
992 test_roundtrip(&m1[..], &m2[..]);
993 assert_ne!(manifest_delta(&m1[..], &m2[..]).len(), 0);
994
995 // changing a line
996 test_roundtrip(&m2[..], &m1[..]);
997 assert_ne!(manifest_delta(&m1[..], &m2[..]).len(), 0);
998 }
999
1000 #[test]
1001 fn test_manifest_diff_complex() {
1002 let m1 = b"a\0abc\nb\0abc\nc\0abc\n";
1003
1004 // Identical, diff should be empty
1005 test_roundtrip(&m1[..], &m1[..]);
1006 assert_eq!(manifest_delta(&m1[..], &m1[..]).len(), 0);
1007
1008 // Removed a path at the start
1009 let m2 = b"b\0abc\nc\0abc\n";
1010 test_roundtrip(&m1[..], &m2[..]);
1011 assert_eq!(manifest_delta(&m1[..], &m2[..]).len(), 12);
1012
1013 // Removed a path in the middle
1014 let m2 = b"a\0abc\nc\0abc\n";
1015 test_roundtrip(&m1[..], &m2[..]);
1016 assert_eq!(manifest_delta(&m1[..], &m2[..]).len(), 12);
1017
1018 // Added a path in the middle
1019 test_roundtrip(&m2[..], &m1[..]);
1020 assert_ne!(manifest_delta(&m2[..], &m1[..]).len(), 0);
1021
1022 // Changed a node/flag in the middle, should replace
1023 let m2 = b"a\0abc\nb\0bcd\nc\0abc\n";
1024 test_roundtrip(&m1[..], &m2[..]);
1025 assert_ne!(manifest_delta(&m1[..], &m2[..]).len(), 0);
1026 }
1027
1028 #[test]
1029 fn test_manifest_diff_actual_cases() {
1030 // Removed two paths in the middle
1031 let m1 = b"a.txt\x00b789fdd96dc2f3bd229c1dd8eedf0fc60e2b68e3\n\
1032 aa.txt\x00a4bdc161c8fbb523c9a60409603f8710ff49a571\n\
1033 b.txt\x001e88685f5ddec574a34c70af492f95b6debc8741\n\
1034 c.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1035 cc.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1036 ccc.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1037 d.txt\x001e88685f5ddec574a34c70af492f95b6debc8741\n\
1038 e.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n";
1039 let m2 = b"a.txt\x00b789fdd96dc2f3bd229c1dd8eedf0fc60e2b68e3\n\
1040 aa.txt\x00a4bdc161c8fbb523c9a60409603f8710ff49a571\n\
1041 c.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1042 cc.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1043 ccc.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1044 e.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n";
1045 test_roundtrip(&m1[..], &m2[..]);
1046 assert_ne!(manifest_delta(&m1[..], &m2[..]).len(), 0);
1047
1048 // Removed two paths and added one
1049 let m2 = b"a.txt\x00b789fdd96dc2f3bd229c1dd8eedf0fc60e2b68e3\n\
1050 aa.txt\x00a4bdc161c8fbb523c9a60409603f8710ff49a571\n\
1051 bb.txt\x0004c6faf8a9fdd848a5304dfc1704749a374dff44\n\
1052 c.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1053 cc.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1054 ccc.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n\
1055 e.txt\x00149da44f2a4e14f488b7bd4157945a9837408c00\n";
1056 test_roundtrip(&m1[..], &m2[..]);
1057 assert_ne!(manifest_delta(&m1[..], &m2[..]).len(), 0);
1058
1059 // Updated the last path
1060 let m1 = b"bar\x00b004912a8510032a0350a74daa2803dadfb00e12\n\
1061 baz\x00354ae8da6e890359ef49ade27b68bbc361f3ca88\n\
1062 foo\x0022fb50216c01fd6a604494be1bcb05c8d2d07641\n";
1063
1064 let m2 = b"bar\x00b004912a8510032a0350a74daa2803dadfb00e12\n\
1065 baz\x00354ae8da6e890359ef49ade27b68bbc361f3ca88\n\
1066 foo\x00263143458f3c42bd4b185a2dc56c5f1593c17c3f\n";
1067 test_roundtrip(&m1[..], &m2[..]);
1068 assert_ne!(manifest_delta(&m1[..], &m2[..]).len(), 0);
1069 }
1070 }