Debian Codegraph @

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

raw
1 use std::collections::HashMap;
2 use std::collections::HashSet;
3 use std::fmt::Debug;
4 use std::ops::Deref;
5 use std::sync::RwLock;
6 use std::sync::RwLockReadGuard;
7 use std::sync::RwLockWriteGuard;
8
9 use bitvec::prelude::*;
10 use byteorder::BigEndian;
11 use byteorder::ByteOrder;
12 use bytes_cast::unaligned;
13 use bytes_cast::BytesCast;
14
15 use super::NodePrefix;
16 use super::RevlogError;
17 use super::RevlogIndex;
18 use super::REVIDX_KNOWN_FLAGS;
19 use super::REVISION_FLAG_DELTA_IS_SNAPSHOT;
20 use crate::dagops;
21 use crate::dyn_bytes::ByteStoreTrunc;
22 use crate::dyn_bytes::DynBytes;
23 use crate::errors::HgError;
24 use crate::revlog::node::Node;
25 use crate::revlog::node::NODE_BYTES_LENGTH;
26 use crate::revlog::node::NULL_NODE;
27 use crate::revlog::node::STORED_NODE_ID_BYTES;
28 use crate::revlog::Revision;
29 use crate::revlog::NULL_REVISION;
30 use crate::utils::u32_u;
31 use crate::BaseRevision;
32 use crate::FastHashMap;
33 use crate::Graph;
34 use crate::GraphError;
35 use crate::UncheckedRevision;
36
37 pub const INDEX_ENTRY_SIZE: usize = 64;
38 pub const INDEX_HEADER_SIZE: usize = 4;
39 pub const COMPRESSION_MODE_INLINE: u8 = 2;
40
41 #[derive(Debug)]
42 pub struct IndexHeader {
43 pub(super) header_bytes: [u8; INDEX_HEADER_SIZE],
44 }
45
46 #[derive(Copy, Clone, Debug)]
47 pub struct IndexHeaderFlags {
48 flags: u16,
49 }
50
51 // Match Python constants
52 pub const FLAG_INLINE_DATA: u16 = 1;
53 pub const FLAG_GENERALDELTA: u16 = 1 << 1;
54 pub const FLAG_FILELOG_META: u16 = 1 << 2;
55 pub const FLAG_DELTA_INFO: u16 = 1 << 3;
56
57 /// Corresponds to the high bits of `_format_flags` in python
58 impl IndexHeaderFlags {
59 pub fn is_inline(self) -> bool {
60 self.flags & FLAG_INLINE_DATA != 0
61 }
62 pub fn uses_generaldelta(self) -> bool {
63 self.flags & FLAG_GENERALDELTA != 0
64 }
65 pub fn uses_filelog_meta(self) -> bool {
66 self.flags & FLAG_FILELOG_META != 0
67 }
68 pub fn uses_delta_info(self) -> bool {
69 self.flags & FLAG_DELTA_INFO != 0
70 }
71 }
72
73 /// Corresponds to the INDEX_HEADER structure,
74 /// which is parsed as a `header` variable in `_loadindex` in `revlog.py`
75 impl IndexHeader {
76 fn format_flags(&self) -> IndexHeaderFlags {
77 // No "unknown flags" check here, unlike in python. Maybe there should
78 // be.
79 IndexHeaderFlags {
80 flags: BigEndian::read_u16(&self.header_bytes[0..2]),
81 }
82 }
83
84 /// The only revlog version currently supported by rhg.
85 const REVLOGV1: u16 = 1;
86
87 /// Corresponds to `_format_version` in Python.
88 fn format_version(&self) -> u16 {
89 BigEndian::read_u16(&self.header_bytes[2..4])
90 }
91
92 pub fn parse(index_bytes: &[u8]) -> Result<IndexHeader, HgError> {
93 if index_bytes.len() < 4 {
94 return Err(HgError::corrupted(
95 "corrupted revlog: can't read the index format header",
96 ));
97 }
98 Ok(IndexHeader {
99 header_bytes: {
100 let bytes: [u8; 4] =
101 index_bytes[0..4].try_into().expect("impossible");
102 bytes
103 },
104 })
105 }
106 }
107
108 /// Abstracts the access to the index bytes since they can be spread between
109 /// the immutable (bytes) part and the mutable (added) part if any appends
110 /// happened. This makes it transparent for the callers.
111 struct IndexData<B> {
112 /// Immutable bytes, most likely taken from disk
113 bytes: B,
114 /// Bytes that were added after reading the index
115 added: Vec<u8>,
116 first_entry: [u8; INDEX_ENTRY_SIZE],
117 }
118
119 impl<B: ByteStoreTrunc> IndexData<B> {
120 pub fn new(bytes: B) -> Self {
121 let mut first_entry = [0; INDEX_ENTRY_SIZE];
122 if bytes.len() >= INDEX_ENTRY_SIZE {
123 first_entry[INDEX_HEADER_SIZE..]
124 .copy_from_slice(&bytes[INDEX_HEADER_SIZE..INDEX_ENTRY_SIZE])
125 }
126 Self { bytes, added: vec![], first_entry }
127 }
128
129 pub fn len(&self) -> usize {
130 self.bytes.len() + self.added.len()
131 }
132
133 fn remove(
134 &mut self,
135 rev: Revision,
136 offsets: Option<&[usize]>,
137 ) -> Result<(), RevlogError> {
138 let rev = rev.0 as usize;
139 let truncation = if let Some(offsets) = offsets {
140 offsets[rev]
141 } else {
142 rev * INDEX_ENTRY_SIZE
143 };
144 if truncation < self.bytes.len() {
145 self.bytes.truncate(truncation);
146 self.added.clear();
147 } else {
148 self.added.truncate(truncation - self.bytes.len());
149 }
150 Ok(())
151 }
152
153 fn is_new(&self) -> bool {
154 self.bytes.is_empty()
155 }
156 }
157
158 impl<B: Deref<Target = [u8]>> std::ops::Index<std::ops::Range<usize>>
159 for IndexData<B>
160 {
161 type Output = [u8];
162
163 fn index(&self, index: std::ops::Range<usize>) -> &Self::Output {
164 let start = index.start;
165 let end = index.end;
166 let immutable_len = self.bytes.len();
167 if start < immutable_len {
168 if end > immutable_len {
169 panic!("index data cannot span existing and added ranges");
170 }
171 &self.bytes[index]
172 } else {
173 &self.added[start - immutable_len..end - immutable_len]
174 }
175 }
176 }
177
178 #[derive(Debug, PartialEq, Eq)]
179 pub struct RevisionDataParams {
180 pub flags: u16,
181 pub data_offset: u64,
182 pub data_compressed_length: i32,
183 pub data_uncompressed_length: i32,
184 pub data_delta_base: i32,
185 pub link_rev: i32,
186 pub parent_rev_1: i32,
187 pub parent_rev_2: i32,
188 pub node_id: [u8; NODE_BYTES_LENGTH],
189 pub _sidedata_offset: u64,
190 pub _sidedata_compressed_length: i32,
191 pub data_compression_mode: u8,
192 pub _sidedata_compression_mode: u8,
193 pub _rank: i32,
194 }
195
196 impl Default for RevisionDataParams {
197 fn default() -> Self {
198 Self {
199 flags: 0,
200 data_offset: 0,
201 data_compressed_length: 0,
202 data_uncompressed_length: 0,
203 data_delta_base: -1,
204 link_rev: -1,
205 parent_rev_1: -1,
206 parent_rev_2: -1,
207 node_id: [0; NODE_BYTES_LENGTH],
208 _sidedata_offset: 0,
209 _sidedata_compressed_length: 0,
210 data_compression_mode: COMPRESSION_MODE_INLINE,
211 _sidedata_compression_mode: COMPRESSION_MODE_INLINE,
212 _rank: -1,
213 }
214 }
215 }
216
217 #[derive(BytesCast)]
218 #[repr(C)]
219 pub struct RevisionDataV1 {
220 data_offset_or_flags: unaligned::U64Be,
221 data_compressed_length: unaligned::I32Be,
222 data_uncompressed_length: unaligned::I32Be,
223 data_delta_base: unaligned::I32Be,
224 link_rev: unaligned::I32Be,
225 parent_rev_1: unaligned::I32Be,
226 parent_rev_2: unaligned::I32Be,
227 node_id: [u8; STORED_NODE_ID_BYTES],
228 }
229
230 fn _static_assert_size_of_revision_data_v1() {
231 let _ = std::mem::transmute::<RevisionDataV1, [u8; 64]>;
232 }
233
234 impl RevisionDataParams {
235 pub fn validate(&self) -> Result<(), RevlogError> {
236 if self.flags & !REVIDX_KNOWN_FLAGS != 0 {
237 return Err(RevlogError::corrupted(format!(
238 "unknown revlog index flags: {}",
239 self.flags
240 )));
241 }
242 if self.data_compression_mode != COMPRESSION_MODE_INLINE {
243 return Err(RevlogError::corrupted(format!(
244 "invalid data compression mode: {}",
245 self.data_compression_mode
246 )));
247 }
248 // FIXME isn't this only for v2 or changelog v2?
249 if self._sidedata_compression_mode != COMPRESSION_MODE_INLINE {
250 return Err(RevlogError::corrupted(format!(
251 "invalid sidedata compression mode: {}",
252 self._sidedata_compression_mode
253 )));
254 }
255 Ok(())
256 }
257
258 pub fn into_v1(self) -> RevisionDataV1 {
259 let data_offset_or_flags = (self.data_offset << 16) | self.flags as u64;
260 let mut node_id = [0; STORED_NODE_ID_BYTES];
261 node_id[..NODE_BYTES_LENGTH].copy_from_slice(&self.node_id);
262 RevisionDataV1 {
263 data_offset_or_flags: data_offset_or_flags.into(),
264 data_compressed_length: self.data_compressed_length.into(),
265 data_uncompressed_length: self.data_uncompressed_length.into(),
266 data_delta_base: self.data_delta_base.into(),
267 link_rev: self.link_rev.into(),
268 parent_rev_1: self.parent_rev_1.into(),
269 parent_rev_2: self.parent_rev_2.into(),
270 node_id,
271 }
272 }
273 }
274
275 /// A Revlog index
276 pub struct Index {
277 bytes: IndexData<DynBytes<'static>>,
278 /// Offsets of starts of index blocks.
279 /// Only needed when the index is interleaved with data.
280 offsets: RwLock<Option<Vec<usize>>>,
281 uses_generaldelta: bool,
282 uses_filelog_meta: bool,
283 uses_delta_info: bool,
284 is_inline: bool,
285 /// Cache of (head_revisions, filtered_revisions)
286 ///
287 /// The head revisions in this index, kept in sync. Should
288 /// be accessed via the [`Self::head_revs`] method.
289 /// The last filtered revisions in this index, used to make sure
290 /// we haven't changed filters when returning the cached `head_revs`.
291 pub(super) head_revs: RwLock<(Vec<Revision>, HashSet<Revision>)>,
292 }
293
294 impl Debug for Index {
295 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296 f.debug_struct("Index")
297 .field("offsets", &self.offsets)
298 .field("uses_generaldelta", &self.uses_generaldelta)
299 .finish()
300 }
301 }
302
303 impl Graph for Index {
304 #[inline(always)]
305 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
306 let err = || GraphError::ParentOutOfRange(rev);
307 let entry = self.get_entry(rev);
308 Ok([
309 self.check_revision(entry.p1()).ok_or_else(err)?,
310 self.check_revision(entry.p2()).ok_or_else(err)?,
311 ])
312 }
313 }
314
315 /// A cache suitable for find_snapshots
316 ///
317 /// Logically equivalent to a mapping whose keys are [`BaseRevision`] and
318 /// values sets of [`BaseRevision`]
319 ///
320 /// TODO the dubious part is insisting that errors must be RevlogError
321 /// we would probably need to sprinkle some magic here, such as an associated
322 /// type that would be `Into<RevlogError>` but even that would not be
323 /// satisfactory, as errors potentially have nothing to do with the revlog.
324 pub trait SnapshotsCache {
325 fn insert_for(
326 &mut self,
327 rev: BaseRevision,
328 value: BaseRevision,
329 ) -> Result<(), RevlogError>;
330 }
331
332 impl SnapshotsCache for FastHashMap<BaseRevision, HashSet<BaseRevision>> {
333 fn insert_for(
334 &mut self,
335 rev: BaseRevision,
336 value: BaseRevision,
337 ) -> Result<(), RevlogError> {
338 let all_values = self.entry(rev).or_default();
339 all_values.insert(value);
340 Ok(())
341 }
342 }
343
344 impl Index {
345 /// Create an index from bytes.
346 /// Calculate the start of each entry when is_inline is true.
347 pub fn new(
348 bytes: DynBytes<'static>,
349 default_header: IndexHeader,
350 ) -> Result<Self, HgError> {
351 let header = if bytes.len() < INDEX_ENTRY_SIZE {
352 default_header
353 } else {
354 IndexHeader::parse(bytes.as_ref())?
355 };
356
357 if header.format_version() != IndexHeader::REVLOGV1 {
358 // A proper new version should have had a repo/store
359 // requirement.
360 return Err(HgError::corrupted("unsupported revlog version"));
361 }
362
363 let uses_generaldelta = header.format_flags().uses_generaldelta();
364 let uses_filelog_meta = header.format_flags().uses_filelog_meta();
365 let uses_delta_info = header.format_flags().uses_delta_info();
366
367 if header.format_flags().is_inline() {
368 let mut offset: usize = 0;
369 let mut offsets = Vec::new();
370
371 while offset + INDEX_ENTRY_SIZE <= bytes.len() {
372 offsets.push(offset);
373 let end = offset + INDEX_ENTRY_SIZE;
374 let entry = IndexEntry { bytes: &bytes[offset..end] };
375
376 offset += INDEX_ENTRY_SIZE + entry.compressed_len() as usize;
377 }
378
379 if offset == bytes.len() {
380 Ok(Self {
381 bytes: IndexData::new(bytes),
382 offsets: RwLock::new(Some(offsets)),
383 uses_generaldelta,
384 uses_filelog_meta,
385 uses_delta_info,
386 is_inline: true,
387 head_revs: RwLock::new((vec![], HashSet::new())),
388 })
389 } else {
390 Err(HgError::corrupted("unexpected inline revlog length"))
391 }
392 } else {
393 Ok(Self {
394 bytes: IndexData::new(bytes),
395 offsets: RwLock::new(None),
396 uses_generaldelta,
397 uses_filelog_meta,
398 uses_delta_info,
399 is_inline: false,
400 head_revs: RwLock::new((vec![], HashSet::new())),
401 })
402 }
403 }
404
405 pub fn uses_generaldelta(&self) -> bool {
406 self.uses_generaldelta
407 }
408
409 pub fn uses_filelog_meta(&self) -> bool {
410 self.uses_filelog_meta
411 }
412
413 pub fn uses_delta_info(&self) -> bool {
414 self.uses_delta_info
415 }
416
417 /// Value of the inline flag.
418 pub fn is_inline(&self) -> bool {
419 self.is_inline
420 }
421
422 /// Return a slice of bytes if `revlog` is inline. Panic if not.
423 pub fn data(&self, start: usize, end: usize) -> &[u8] {
424 if !self.is_inline() {
425 panic!("tried to access data in the index of a revlog that is not inline");
426 }
427 &self.bytes[start..end]
428 }
429
430 /// Return number of entries of the revlog index.
431 pub fn len(&self) -> usize {
432 if self.is_inline() {
433 (*self.get_offsets())
434 .as_ref()
435 .expect("inline should have offsets")
436 .len()
437 } else {
438 self.bytes.len() / INDEX_ENTRY_SIZE
439 }
440 }
441
442 /// Same as `rev_from_node`, without using a persistent nodemap
443 ///
444 /// This is used as fallback when a persistent nodemap is not present.
445 /// This happens when the persistent-nodemap experimental feature is not
446 /// enabled, or for small revlogs.
447 pub fn rev_from_node_no_persistent_nodemap(
448 &self,
449 node: NodePrefix,
450 ) -> Result<Revision, RevlogError> {
451 // Linear scan of the revlog
452 // TODO: consider building a non-persistent nodemap in memory to
453 // optimize these cases.
454 let mut found_by_prefix = None;
455 for rev in (-1..self.len() as BaseRevision).rev() {
456 let rev = Revision(rev as BaseRevision);
457 let candidate_node = if rev == Revision(-1) {
458 NULL_NODE
459 } else {
460 let index_entry = self.get_entry(rev);
461 *index_entry.hash()
462 };
463 if node == candidate_node {
464 return Ok(rev);
465 }
466 if node.is_prefix_of(&candidate_node) {
467 if found_by_prefix.is_some() {
468 return Err(RevlogError::AmbiguousPrefix(format!(
469 "{:x}",
470 node
471 )));
472 }
473 found_by_prefix = Some(rev)
474 }
475 }
476 found_by_prefix
477 .ok_or_else(|| RevlogError::InvalidRevision(format!("{:x}", node)))
478 }
479
480 pub fn get_offsets(&self) -> RwLockReadGuard<Option<Vec<usize>>> {
481 assert!(self.is_inline());
482 {
483 // Wrap in a block to drop the read guard
484 let mut offsets = self.offsets.write().unwrap();
485 if offsets.is_none() {
486 offsets.replace(inline_scan(&self.bytes.bytes).1);
487 }
488 }
489 self.offsets.read().unwrap()
490 }
491
492 pub fn get_offsets_mut(&mut self) -> RwLockWriteGuard<Option<Vec<usize>>> {
493 assert!(self.is_inline());
494 let mut offsets = self.offsets.write().unwrap();
495 if offsets.is_none() {
496 offsets.replace(inline_scan(&self.bytes.bytes).1);
497 }
498 offsets
499 }
500
501 /// Returns `true` if the `Index` has zero `entries`.
502 pub fn is_empty(&self) -> bool {
503 self.len() == 0
504 }
505
506 /// Return the index entry corresponding to the given revision or `None`
507 /// for [`NULL_REVISION`]
508 ///
509 /// The specified revision being of the checked type, it always exists
510 /// if it was validated by this index.
511 #[inline(always)]
512 pub fn get_entry(&self, rev: Revision) -> IndexEntry {
513 if rev == NULL_REVISION {
514 IndexEntry { bytes: NULL_ENTRY }
515 } else if rev.0 == 0 {
516 IndexEntry { bytes: &self.bytes.first_entry[..] }
517 } else if self.is_inline() {
518 self.get_entry_inline(rev)
519 } else {
520 self.get_entry_separated(rev)
521 }
522 }
523
524 /// Return the binary content of the index entry for the given revision
525 pub fn entry_binary(&self, rev: Revision) -> &[u8] {
526 let bytes = self.get_entry(rev).as_bytes();
527 if rev.0 == 0 {
528 &bytes[4..]
529 } else {
530 bytes
531 }
532 }
533
534 pub fn entry_as_params(
535 &self,
536 rev: UncheckedRevision,
537 ) -> Option<RevisionDataParams> {
538 let rev = self.check_revision(rev)?;
539 let e = self.get_entry(rev);
540 Some(RevisionDataParams {
541 flags: e.flags(),
542 data_offset: if rev.0 == 0 && !self.bytes.is_new() {
543 e.flags() as u64
544 } else {
545 e.raw_offset()
546 },
547 data_compressed_length: e
548 .compressed_len()
549 .try_into()
550 .unwrap_or_else(|_| {
551 // Python's `unionrepo` sets the compressed length to
552 // be `-1` (or `u32::MAX` if
553 // transmuted to `u32`) because it
554 // cannot know the correct compressed length of a given
555 // revision. I'm not sure if this is true, but having
556 // this edge case won't hurt
557 // other use cases, let's handle it.
558 assert_eq!(e.compressed_len(), u32::MAX);
559 NULL_REVISION.0
560 }),
561 data_uncompressed_length: e.uncompressed_len(),
562 data_delta_base: e.base_revision_or_base_of_delta_chain().0,
563 link_rev: e.link_revision().0,
564 parent_rev_1: e.p1().0,
565 parent_rev_2: e.p2().0,
566 node_id: e.hash().as_bytes().try_into().unwrap(),
567 ..Default::default()
568 })
569 }
570
571 fn get_entry_inline(&self, rev: Revision) -> IndexEntry {
572 let offsets = &self.get_offsets();
573 let offsets = offsets.as_ref().expect("inline should have offsets");
574 let start = offsets[rev.0 as usize];
575 let end = start + INDEX_ENTRY_SIZE;
576 let bytes = &self.bytes[start..end];
577
578 IndexEntry { bytes }
579 }
580
581 fn get_entry_separated(&self, rev: Revision) -> IndexEntry {
582 let start = rev.0 as usize * INDEX_ENTRY_SIZE;
583 let end = start + INDEX_ENTRY_SIZE;
584 let bytes = &self.bytes[start..end];
585
586 IndexEntry { bytes }
587 }
588
589 /// Return the head revisions of this index
590 pub fn head_revs(&self) -> Result<Vec<Revision>, GraphError> {
591 self.head_revs_advanced(&HashSet::new(), None, false)
592 .map(|h| h.unwrap())
593 }
594
595 /// Return the head revisions of this index
596 pub fn head_revs_advanced(
597 &self,
598 filtered_revs: &HashSet<Revision>,
599 stop_rev: Option<Revision>,
600 py_shortcut: bool,
601 ) -> Result<Option<Vec<Revision>>, GraphError> {
602 {
603 let guard = self
604 .head_revs
605 .read()
606 .expect("RwLock on Index.head_revs should not be poisoned");
607 let self_head_revs = &guard.0;
608 let self_filtered_revs = &guard.1;
609 if !self_head_revs.is_empty()
610 && filtered_revs == self_filtered_revs
611 && stop_rev.is_none()
612 {
613 if py_shortcut {
614 // Don't copy the revs since we've already cached them
615 // on the Python side.
616 return Ok(None);
617 } else {
618 return Ok(Some(self_head_revs.to_owned()));
619 }
620 }
621 }
622
623 let (as_vec, cachable) = if self.is_empty() {
624 (vec![NULL_REVISION], true)
625 } else {
626 let _trace = tracing::debug_span!("heads cache miss").entered();
627 let length: usize = match stop_rev {
628 Some(r) => r.0 as usize,
629 None => self.len(),
630 };
631 let cachable = self.len() == length;
632 let mut not_heads = bitvec![0; length];
633 dagops::retain_heads_fast(
634 self,
635 not_heads.as_mut_bitslice(),
636 filtered_revs,
637 )?;
638 (
639 not_heads
640 .into_iter()
641 .enumerate()
642 .filter_map(|(idx, is_not_head)| {
643 if is_not_head {
644 None
645 } else {
646 Some(Revision(idx as BaseRevision))
647 }
648 })
649 .collect(),
650 cachable,
651 )
652 };
653 if cachable {
654 *self
655 .head_revs
656 .write()
657 .expect("RwLock on Index.head_revs should not be poisoned") =
658 (as_vec.to_owned(), filtered_revs.to_owned());
659 }
660 Ok(Some(as_vec))
661 }
662
663 /// Python-specific shortcut to save on PyList creation
664 pub fn head_revs_shortcut(
665 &self,
666 ) -> Result<Option<Vec<Revision>>, GraphError> {
667 self.head_revs_advanced(&HashSet::new(), None, true)
668 }
669
670 /// Return the heads removed and added by advancing from `begin` to `end`.
671 /// In revset language, we compute:
672 /// - `heads(:begin)-heads(:end)`
673 /// - `heads(:end)-heads(:begin)`
674 pub fn head_revs_diff(
675 &self,
676 begin: Revision,
677 end: Revision,
678 ) -> Result<(Vec<Revision>, Vec<Revision>), GraphError> {
679 let mut heads_added = vec![];
680 let mut heads_removed = vec![];
681
682 let mut acc = HashSet::new();
683 let Revision(begin) = begin;
684 let Revision(end) = end;
685 let mut i = end;
686
687 while i > begin {
688 // acc invariant:
689 // `j` is in the set iff `j <= i` and it has children
690 // among `i+1..end` (inclusive)
691 if !acc.remove(&i) {
692 heads_added.push(Revision(i));
693 }
694 for Revision(parent) in self.parents(Revision(i))? {
695 acc.insert(parent);
696 }
697 i -= 1;
698 }
699
700 // At this point `acc` contains old revisions that gained new children.
701 // We need to check if they had any children before. If not, those
702 // revisions are the removed heads.
703 while !acc.is_empty() {
704 // acc invariant:
705 // `j` is in the set iff `j <= i` and it has children
706 // among `begin+1..end`, but not among `i+1..begin` (inclusive)
707
708 assert!(i >= -1); // yes, `-1` can also be a head if the repo is empty
709 if acc.remove(&i) {
710 heads_removed.push(Revision(i));
711 }
712 for Revision(parent) in self.parents(Revision(i))? {
713 acc.remove(&parent);
714 }
715 i -= 1;
716 }
717
718 Ok((heads_removed, heads_added))
719 }
720
721 /// Obtain the delta chain for a revision.
722 ///
723 /// `stop_rev` specifies a revision to stop at. If not specified, we
724 /// stop at the base of the chain.
725 ///
726 /// Returns a 2-tuple of (chain, stopped) where `chain` is a vec of
727 /// revs in ascending order and `stopped` is a bool indicating whether
728 /// `stoprev` was hit.
729 pub fn delta_chain(
730 &self,
731 rev: Revision,
732 stop_rev: Option<Revision>,
733 ) -> Result<(Vec<Revision>, bool), HgError> {
734 let mut current_rev = rev;
735 let mut entry = self.get_entry(rev);
736 let mut chain = vec![];
737 let using_general_delta = self.uses_generaldelta();
738 while current_rev.0 != entry.base_revision_or_base_of_delta_chain().0
739 && stop_rev.map(|r| r != current_rev).unwrap_or(true)
740 {
741 if entry.compressed_len() > 0 {
742 // skip over empty delta, they don't contribute to the restored
743 // content.
744 chain.push(current_rev);
745 }
746 let new_rev = if using_general_delta {
747 entry.base_revision_or_base_of_delta_chain()
748 } else {
749 UncheckedRevision(current_rev.0 - 1)
750 };
751 current_rev = self.check_revision(new_rev).ok_or_else(|| {
752 HgError::corrupted(format!("Revision {new_rev} out of range"))
753 })?;
754 if current_rev.0 == NULL_REVISION.0 {
755 break;
756 }
757 entry = self.get_entry(current_rev);
758 }
759
760 let stopped = if stop_rev.map(|r| current_rev == r).unwrap_or(false) {
761 true
762 } else {
763 chain.push(current_rev);
764 false
765 };
766 chain.reverse();
767 Ok((chain, stopped))
768 }
769
770 pub fn find_snapshots(
771 &self,
772 start_rev: UncheckedRevision,
773 end_rev: UncheckedRevision,
774 cache: &mut impl SnapshotsCache,
775 ) -> Result<(), RevlogError> {
776 let mut start_rev = start_rev.0;
777 let mut end_rev = end_rev.0;
778 end_rev += 1;
779 let len = self.len().try_into().unwrap();
780 if end_rev > len {
781 end_rev = len;
782 }
783 if start_rev < 0 {
784 start_rev = 0;
785 }
786 for rev in start_rev..end_rev {
787 if !self.is_snapshot_unchecked(Revision(rev))? {
788 continue;
789 }
790 let mut base = self
791 .get_entry(Revision(rev))
792 .base_revision_or_base_of_delta_chain();
793 if base.0 == rev {
794 base = NULL_REVISION.into();
795 }
796 cache.insert_for(base.0, rev)?;
797 }
798 Ok(())
799 }
800
801 fn clear_head_revs(&self) {
802 self.head_revs
803 .write()
804 .expect("RwLock on Index.head_revs should not be poisoined")
805 .0
806 .clear()
807 }
808
809 /// TODO move this to the trait probably, along with other things
810 pub fn append(
811 &mut self,
812 revision_data: RevisionDataParams,
813 ) -> Result<(), RevlogError> {
814 revision_data.validate()?;
815 let entry_v1 = revision_data.into_v1();
816 let entry_bytes = entry_v1.as_bytes();
817 if self.bytes.len() == 0 {
818 self.bytes.first_entry[INDEX_HEADER_SIZE..].copy_from_slice(
819 &entry_bytes[INDEX_HEADER_SIZE..INDEX_ENTRY_SIZE],
820 )
821 }
822 if self.is_inline() {
823 let new_offset = self.bytes.len();
824 if let Some(offsets) = &mut *self.get_offsets_mut() {
825 offsets.push(new_offset)
826 }
827 }
828 self.bytes.added.extend(entry_bytes);
829 self.clear_head_revs();
830 Ok(())
831 }
832
833 pub fn pack_header(&self, header: i32) -> [u8; 4] {
834 header.to_be_bytes()
835 }
836
837 pub fn remove(&mut self, rev: Revision) -> Result<(), RevlogError> {
838 let offsets = if self.is_inline() {
839 self.get_offsets().clone()
840 } else {
841 None
842 };
843 self.bytes.remove(rev, offsets.as_deref())?;
844 if self.is_inline() {
845 if let Some(offsets) = &mut *self.get_offsets_mut() {
846 offsets.truncate(rev.0 as usize)
847 }
848 }
849 self.clear_head_revs();
850 Ok(())
851 }
852
853 pub fn clear_caches(&self) {
854 // We need to get the 'inline' value from Python at init and use this
855 // instead of offsets to determine whether we're inline since we might
856 // clear caches. This implies re-populating the offsets on-demand.
857 *self
858 .offsets
859 .write()
860 .expect("RwLock on Index.offsets should not be poisoed") = None;
861 self.clear_head_revs();
862 }
863
864 /// Unchecked version of `is_snapshot`.
865 /// Assumes the caller checked that `rev` is within a valid revision range.
866 pub fn is_snapshot_unchecked(
867 &self,
868 mut rev: Revision,
869 ) -> Result<bool, RevlogError> {
870 if rev == NULL_REVISION {
871 Ok(true)
872 } else if self.uses_delta_info() {
873 let entry = self.get_entry(rev);
874 Ok((entry.flags() & REVISION_FLAG_DELTA_IS_SNAPSHOT) != 0)
875 } else {
876 while rev.0 >= 0 {
877 let entry = self.get_entry(rev);
878 let mut base = entry.base_revision_or_base_of_delta_chain().0;
879 if base == rev.0 {
880 base = NULL_REVISION.0;
881 }
882 if base == NULL_REVISION.0 {
883 return Ok(true);
884 }
885 let [mut p1, mut p2] = self
886 .parents(rev)
887 .map_err(|e| RevlogError::InvalidRevision(e.to_string()))?;
888 while p1 != NULL_REVISION {
889 let p1_entry = self.get_entry(p1);
890 if p1_entry.compressed_len() != 0 || p1.0 == 0 {
891 break;
892 }
893 let parent_base =
894 p1_entry.base_revision_or_base_of_delta_chain();
895 if parent_base.0 == p1.0 {
896 break;
897 }
898 p1 = self.check_revision(parent_base).ok_or_else(|| {
899 RevlogError::InvalidRevision(parent_base.to_string())
900 })?;
901 }
902 while p2 != NULL_REVISION {
903 let p2_entry = self.get_entry(p2);
904 if p2_entry.compressed_len() != 0 || p2.0 == 0 {
905 break;
906 }
907 let parent_base =
908 p2_entry.base_revision_or_base_of_delta_chain();
909 if parent_base.0 == p2.0 {
910 break;
911 }
912 p2 = self.check_revision(parent_base).ok_or_else(|| {
913 RevlogError::InvalidRevision(parent_base.to_string())
914 })?;
915 }
916 if base == p1.0 || base == p2.0 {
917 return Ok(false);
918 }
919 rev = self.check_revision(base.into()).ok_or_else(|| {
920 RevlogError::InvalidRevision(base.to_string())
921 })?;
922 }
923 Ok(rev == NULL_REVISION)
924 }
925 }
926
927 /// Return whether the given revision is a snapshot. Returns an error if
928 /// `rev` is not within a valid revision range.
929 pub fn is_snapshot(
930 &self,
931 rev: UncheckedRevision,
932 ) -> Result<bool, RevlogError> {
933 let rev = self
934 .check_revision(rev)
935 .ok_or_else(|| RevlogError::corrupted("test"))?;
936 self.is_snapshot_unchecked(rev)
937 }
938
939 /// Slice revs to reduce the amount of unrelated data to be read from disk.
940 ///
941 /// The index is sliced into groups that should be read in one time.
942 ///
943 /// The initial chunk is sliced until the overall density
944 /// (payload/chunks-span ratio) is above `target_density`.
945 /// No gap smaller than `min_gap_size` is skipped.
946 pub fn slice_chunk_to_density<'a>(
947 &'a self,
948 revs: &'a [Revision],
949 target_density: f64,
950 min_gap_size: usize,
951 ) -> Vec<&'a [Revision]> {
952 if revs.is_empty() {
953 return vec![];
954 }
955 if revs.len() == 1 {
956 return vec![revs];
957 }
958 let delta_chain_span = self.segment_span(revs);
959 if delta_chain_span < min_gap_size {
960 return vec![revs];
961 }
962 let mut read_data = delta_chain_span;
963 let chain_payload: u32 =
964 revs.iter().map(|r| self.get_entry(*r).compressed_len()).sum();
965 let mut density = if delta_chain_span > 0 {
966 chain_payload as f64 / delta_chain_span as f64
967 } else {
968 1.0
969 };
970
971 if density >= target_density {
972 return vec![revs];
973 }
974
975 // Store the gaps in a heap to have them sorted by decreasing size
976 let mut gaps = Vec::new();
977 let mut previous_end = None;
978
979 for (i, rev) in revs.iter().enumerate() {
980 let entry = self.get_entry(*rev);
981 let start = self.start(*rev, &entry);
982 let length = entry.compressed_len();
983
984 // Skip empty revisions to form larger holes
985 if length == 0 {
986 continue;
987 }
988
989 if let Some(end) = previous_end {
990 let gap_size = start - end;
991 // Only consider holes that are large enough
992 if gap_size > min_gap_size {
993 gaps.push((gap_size, i));
994 }
995 }
996 previous_end = Some(start + length as usize);
997 }
998 if gaps.is_empty() {
999 return vec![revs];
1000 }
1001 // sort the gaps to pop them from largest to small
1002 gaps.sort_unstable();
1003
1004 // Collect the indices of the largest holes until
1005 // the density is acceptable
1006 let mut selected = vec![];
1007 while let Some((gap_size, gap_id)) = gaps.pop() {
1008 if density >= target_density {
1009 break;
1010 }
1011 selected.push(gap_id);
1012
1013 // The gap sizes are stored as negatives to be sorted decreasingly
1014 // by the heap
1015 read_data -= gap_size;
1016 density = if read_data > 0 {
1017 chain_payload as f64 / read_data as f64
1018 } else {
1019 1.0
1020 };
1021 if density >= target_density {
1022 break;
1023 }
1024 }
1025 selected.sort_unstable();
1026 selected.push(revs.len());
1027
1028 // Cut the revs at collected indices
1029 let mut previous_idx = 0;
1030 let mut chunks = vec![];
1031 for idx in selected {
1032 let chunk = self.trim_chunk(revs, previous_idx, idx);
1033 if !chunk.is_empty() {
1034 chunks.push(chunk);
1035 }
1036 previous_idx = idx;
1037 }
1038 let chunk = self.trim_chunk(revs, previous_idx, revs.len());
1039 if !chunk.is_empty() {
1040 chunks.push(chunk);
1041 }
1042
1043 chunks
1044 }
1045
1046 /// Get the byte span of a segment of sorted revisions.
1047 ///
1048 /// Occurrences of [`NULL_REVISION`] are ignored at the beginning of
1049 /// the `revs` segment.
1050 ///
1051 /// panics:
1052 /// - if `revs` is empty or only made of `NULL_REVISION`
1053 /// - if cannot retrieve entry for the last or first not null element of
1054 /// `revs`.
1055 fn segment_span(&self, revs: &[Revision]) -> usize {
1056 if revs.is_empty() {
1057 return 0;
1058 }
1059 let last_rev = revs[revs.len() - 1];
1060 let last_entry = self.get_entry(last_rev);
1061 let last_start = self.start(last_rev, &last_entry);
1062 let end = last_start + u32_u(last_entry.compressed_len());
1063
1064 let first_rev = revs[0];
1065 let first_entry = self.get_entry(first_rev);
1066 let start = self.start(first_rev, &first_entry);
1067 end - start
1068 }
1069
1070 /// Returns `&revs[startidx..endidx]` without empty trailing revs
1071 fn trim_chunk<'a>(
1072 &'a self,
1073 revs: &'a [Revision],
1074 start: usize,
1075 mut end: usize,
1076 ) -> &'a [Revision] {
1077 // Trim empty revs at the end, except the very first rev of a chain
1078 let last_rev = revs[end - 1].0;
1079 if last_rev < self.len() as BaseRevision {
1080 while end > 1
1081 && end > start
1082 && self.get_entry(revs[end - 1]).compressed_len() == 0
1083 {
1084 end -= 1
1085 }
1086 }
1087 &revs[start..end]
1088 }
1089
1090 /// Computes the set of revisions for each non-public phase from `roots`,
1091 /// which are the last known roots for each non-public phase.
1092 pub fn compute_phases_map_sets(
1093 &self,
1094 roots: HashMap<Phase, Vec<Revision>>,
1095 ) -> Result<(usize, RootsPerPhase), GraphError> {
1096 let mut phases = vec![Phase::Public; self.len()];
1097 let mut min_phase_rev = NULL_REVISION;
1098
1099 for phase in Phase::non_public_phases() {
1100 if let Some(phase_roots) = roots.get(phase) {
1101 let min_rev =
1102 self.add_roots_get_min(phase_roots, &mut phases, *phase);
1103 if min_rev != NULL_REVISION
1104 && (min_phase_rev == NULL_REVISION
1105 || min_rev < min_phase_rev)
1106 {
1107 min_phase_rev = min_rev;
1108 }
1109 } else {
1110 continue;
1111 };
1112 }
1113 let mut phase_sets: RootsPerPhase = Default::default();
1114
1115 if min_phase_rev == NULL_REVISION {
1116 min_phase_rev = Revision(self.len() as BaseRevision);
1117 }
1118
1119 for rev in min_phase_rev.0..self.len() as BaseRevision {
1120 let rev = Revision(rev);
1121 let [p1, p2] = self.parents(rev)?;
1122
1123 if p1.0 >= 0 && phases[p1.0 as usize] > phases[rev.0 as usize] {
1124 phases[rev.0 as usize] = phases[p1.0 as usize];
1125 }
1126 if p2.0 >= 0 && phases[p2.0 as usize] > phases[rev.0 as usize] {
1127 phases[rev.0 as usize] = phases[p2.0 as usize];
1128 }
1129 let set = match phases[rev.0 as usize] {
1130 Phase::Public => continue,
1131 phase => &mut phase_sets[phase as usize - 1],
1132 };
1133 set.push(rev);
1134 }
1135
1136 Ok((self.len(), phase_sets))
1137 }
1138
1139 fn add_roots_get_min(
1140 &self,
1141 phase_roots: &[Revision],
1142 phases: &mut [Phase],
1143 phase: Phase,
1144 ) -> Revision {
1145 let mut min_rev = NULL_REVISION;
1146
1147 for root in phase_roots {
1148 phases[root.0 as usize] = phase;
1149 if min_rev == NULL_REVISION || min_rev > *root {
1150 min_rev = *root;
1151 }
1152 }
1153 min_rev
1154 }
1155
1156 /// Return `(heads(::(<roots> and <roots>::<heads>)))`
1157 /// If `include_path` is `true`, return `(<roots>::<heads>)`."""
1158 ///
1159 /// `min_root` and `roots` are unchecked since they are just used as
1160 /// a bound or for comparison and don't need to represent a valid revision.
1161 /// In practice, the only invalid revision passed is the working directory
1162 /// revision ([`i32::MAX`]).
1163 pub fn reachable_roots(
1164 &self,
1165 min_root: UncheckedRevision,
1166 mut heads: Vec<Revision>,
1167 roots: HashSet<UncheckedRevision>,
1168 include_path: bool,
1169 ) -> Result<HashSet<Revision>, GraphError> {
1170 if roots.is_empty() {
1171 return Ok(HashSet::new());
1172 }
1173 let mut reachable = HashSet::new();
1174 let mut seen = HashMap::new();
1175
1176 while let Some(rev) = heads.pop() {
1177 if roots.contains(&rev.into()) {
1178 reachable.insert(rev);
1179 if !include_path {
1180 continue;
1181 }
1182 }
1183 let parents = self.parents(rev)?;
1184 seen.insert(rev, parents);
1185 for parent in parents {
1186 if parent.0 >= min_root.0 && !seen.contains_key(&parent) {
1187 heads.push(parent);
1188 }
1189 }
1190 }
1191 if !include_path {
1192 return Ok(reachable);
1193 }
1194 let mut revs: Vec<_> = seen.keys().collect();
1195 revs.sort_unstable();
1196 for rev in revs {
1197 for parent in seen[rev] {
1198 if reachable.contains(&parent) {
1199 reachable.insert(*rev);
1200 }
1201 }
1202 }
1203 Ok(reachable)
1204 }
1205
1206 /// Given a (possibly overlapping) set of revs, return all the
1207 /// common ancestors heads: `heads(::args[0] and ::a[1] and ...)`
1208 pub fn common_ancestor_heads(
1209 &self,
1210 revisions: &[Revision],
1211 ) -> Result<Vec<Revision>, GraphError> {
1212 // given that revisions is expected to be small, we find this shortcut
1213 // potentially acceptable, especially given that `hg-pyo3` could
1214 // very much bypass this, constructing a vector of unique values from
1215 // the onset.
1216 let as_set: HashSet<Revision> = revisions.iter().copied().collect();
1217 // Besides deduplicating, the C version also implements the shortcut
1218 // for `NULL_REVISION`:
1219 if as_set.contains(&NULL_REVISION) {
1220 return Ok(vec![]);
1221 }
1222
1223 let revisions: Vec<Revision> = as_set.into_iter().collect();
1224
1225 if revisions.len() < 8 {
1226 self.find_gca_candidates::<u8>(&revisions)
1227 } else if revisions.len() < 64 {
1228 self.find_gca_candidates::<u64>(&revisions)
1229 } else {
1230 self.find_gca_candidates::<NonStaticPoisonableBitSet>(&revisions)
1231 }
1232 }
1233
1234 pub fn ancestors(
1235 &self,
1236 revisions: &[Revision],
1237 ) -> Result<Vec<Revision>, GraphError> {
1238 self.find_deepest_revs(&self.common_ancestor_heads(revisions)?)
1239 }
1240
1241 /// Given a disjoint set of revs, return all candidates for the
1242 /// greatest common ancestor. In revset notation, this is the set
1243 /// `heads(::a and ::b and ...)`
1244 fn find_gca_candidates<BS: PoisonableBitSet + Clone>(
1245 &self,
1246 revs: &[Revision],
1247 ) -> Result<Vec<Revision>, GraphError> {
1248 if revs.is_empty() {
1249 return Ok(vec![]);
1250 }
1251 let revcount = revs.len();
1252 let mut candidates = vec![];
1253 let max_rev = revs.iter().max().unwrap();
1254
1255 let mut seen = BS::vec_of_empty(revs.len(), (max_rev.0 + 1) as usize);
1256
1257 for (idx, rev) in revs.iter().enumerate() {
1258 seen[rev.0 as usize].add(idx);
1259 }
1260 let mut current_rev = *max_rev;
1261 // Number of revisions whose inspection in the main loop
1262 // will give a result or trigger inspection of other revisions
1263 let mut interesting = revcount;
1264
1265 // The algorithm works on a vector of bit sets, indexed by revision
1266 // numbers and iterated on reverse order.
1267 // An entry in this vector is poisoned if and only if the corresponding
1268 // revision is a common, yet not maximal ancestor.
1269
1270 // The principle of the algorithm is as follows:
1271 // For a revision `r`, when entering the loop, `seen[r]` is either
1272 // poisoned or the sub set of `revs` of which `r` is an ancestor.
1273 // In this sub set is full, then `r` is a solution and its parents
1274 // have to be poisoned.
1275 //
1276 // At each iteration, the bit sets of the parents are updated by
1277 // union with `seen[r]`.
1278 // As we walk the index from the end, we are sure we have encountered
1279 // all children of `r` before `r`, hence we know that `seen[r]` is
1280 // fully computed.
1281 //
1282 // On top of that there are several optimizations that make reading
1283 // less obvious than the comment above:
1284 // - The `interesting` counter allows to break early
1285 // - The loop starts from `max(revs)`
1286 // - Early return in case it is detected that one of the incoming revs
1287 // is a common ancestor of all of them.
1288 while current_rev.0 >= 0 && interesting > 0 {
1289 let current_seen = seen[current_rev.0 as usize].clone();
1290
1291 if current_seen.is_empty() {
1292 current_rev = Revision(current_rev.0 - 1);
1293 continue;
1294 }
1295 let mut poison = current_seen.is_poisoned();
1296 if !poison {
1297 interesting -= 1;
1298 if current_seen.is_full_range(revcount) {
1299 candidates.push(current_rev);
1300 poison = true;
1301
1302 // Being a common ancestor, if `current_rev` is among
1303 // the input revisions, it is *the* answer.
1304 for rev in revs {
1305 if *rev == current_rev {
1306 return Ok(candidates);
1307 }
1308 }
1309 }
1310 }
1311 for parent in self.parents(current_rev)? {
1312 if parent == NULL_REVISION {
1313 continue;
1314 }
1315 let parent_seen = &mut seen[parent.0 as usize];
1316 if poison {
1317 // this block is logically equivalent to poisoning parent
1318 // and counting it as non interesting if it
1319 // has been seen before (hence counted then as interesting)
1320 if !parent_seen.is_empty() && !parent_seen.is_poisoned() {
1321 interesting -= 1;
1322 }
1323 parent_seen.poison();
1324 } else {
1325 if parent_seen.is_empty() {
1326 interesting += 1;
1327 }
1328 parent_seen.union(&current_seen);
1329 }
1330 }
1331
1332 current_rev = Revision(current_rev.0 - 1);
1333 }
1334
1335 Ok(candidates)
1336 }
1337
1338 /// Given a disjoint set of revs, return the subset with the longest path
1339 /// to the root.
1340 fn find_deepest_revs(
1341 &self,
1342 revs: &[Revision],
1343 ) -> Result<Vec<Revision>, GraphError> {
1344 // TODO replace this all with just comparing rank?
1345 // Also, the original implementations in C/Python are cryptic, not
1346 // even sure we actually need this?
1347 if revs.len() <= 1 {
1348 return Ok(revs.to_owned());
1349 }
1350 let max_rev = revs.iter().max().unwrap().0;
1351 let mut interesting = HashMap::new();
1352 let mut seen = vec![0; max_rev as usize + 1];
1353 let mut depth = vec![0; max_rev as usize + 1];
1354 let mut mapping = vec![];
1355 let mut revs = revs.to_owned();
1356 revs.sort_unstable();
1357
1358 for (idx, rev) in revs.iter().enumerate() {
1359 depth[rev.0 as usize] = 1;
1360 let shift = 1 << idx;
1361 seen[rev.0 as usize] = shift;
1362 interesting.insert(shift, 1);
1363 mapping.push((shift, *rev));
1364 }
1365
1366 let mut current_rev = Revision(max_rev);
1367 while current_rev.0 >= 0 && interesting.len() > 1 {
1368 let current_depth = depth[current_rev.0 as usize];
1369 if current_depth == 0 {
1370 current_rev = Revision(current_rev.0 - 1);
1371 continue;
1372 }
1373
1374 let current_seen = seen[current_rev.0 as usize];
1375 for parent in self.parents(current_rev)? {
1376 if parent == NULL_REVISION {
1377 continue;
1378 }
1379 let parent_seen = seen[parent.0 as usize];
1380 let parent_depth = depth[parent.0 as usize];
1381 if parent_depth <= current_depth {
1382 depth[parent.0 as usize] = current_depth + 1;
1383 if parent_seen != current_seen {
1384 *interesting.get_mut(&current_seen).unwrap() += 1;
1385 seen[parent.0 as usize] = current_seen;
1386 if parent_seen != 0 {
1387 let parent_interesting =
1388 interesting.get_mut(&parent_seen).unwrap();
1389 *parent_interesting -= 1;
1390 if *parent_interesting == 0 {
1391 interesting.remove(&parent_seen);
1392 }
1393 }
1394 }
1395 } else if current_depth == parent_depth - 1 {
1396 let either_seen = parent_seen | current_seen;
1397 if either_seen == parent_seen {
1398 continue;
1399 }
1400 seen[parent.0 as usize] = either_seen;
1401 interesting
1402 .entry(either_seen)
1403 .and_modify(|v| *v += 1)
1404 .or_insert(1);
1405 *interesting.get_mut(&parent_seen).unwrap() -= 1;
1406 if interesting[&parent_seen] == 0 {
1407 interesting.remove(&parent_seen);
1408 }
1409 }
1410 }
1411 *interesting.get_mut(&current_seen).unwrap() -= 1;
1412 if interesting[&current_seen] == 0 {
1413 interesting.remove(&current_seen);
1414 }
1415
1416 current_rev = Revision(current_rev.0 - 1);
1417 }
1418
1419 if interesting.len() != 1 {
1420 return Ok(vec![]);
1421 }
1422 let mask = interesting.keys().next().unwrap();
1423
1424 Ok(mapping
1425 .into_iter()
1426 .filter_map(|(shift, rev)| {
1427 if (mask & shift) != 0 {
1428 return Some(rev);
1429 }
1430 None
1431 })
1432 .collect())
1433 }
1434
1435 /// Return the offset into the data corresponding to `rev` (in the index
1436 /// file if inline, in the data file otherwise). `entry` must be the entry
1437 /// for `rev`: the API is done this way to reduce the number of lookups
1438 /// since we sometimes already have the entry, and because very few places
1439 /// actually use this function.
1440 #[inline(always)]
1441 pub fn start(&self, rev: Revision, entry: &IndexEntry<'_>) -> usize {
1442 #[cfg(debug_assertions)]
1443 {
1444 assert_eq!(&self.get_entry(rev), entry);
1445 }
1446 let offset = entry.offset();
1447 if self.is_inline() {
1448 offset + ((rev.0 as usize + 1) * INDEX_ENTRY_SIZE)
1449 } else {
1450 offset
1451 }
1452 }
1453 }
1454
1455 /// The kind of functionality needed by find_gca_candidates
1456 ///
1457 /// This is a bit mask which can be declared to be "poisoned", which callers
1458 /// interpret to break out of some loops.
1459 ///
1460 /// The maximum capacity of the bit mask is up to the actual implementation
1461 trait PoisonableBitSet: Sized + PartialEq {
1462 /// Return a vector of exactly n elements, initialized to be empty.
1463 ///
1464 /// Optimization can vastly depend on implementation. Those being `Copy`
1465 /// and having constant capacity typically can have a very simple
1466 /// implementation.
1467 fn vec_of_empty(sets_size: usize, vec_len: usize) -> Vec<Self>;
1468
1469 /// The size of the bit mask in memory
1470 #[allow(unused)]
1471 fn size(&self) -> usize;
1472
1473 /// The number of elements that can be represented in the set.
1474 ///
1475 /// Another way to put it is that it is the highest integer `C` such that
1476 /// the set is guaranteed to always be a subset of the integer range
1477 /// `[0, C)`
1478 #[allow(unused)]
1479 fn capacity(&self) -> usize;
1480
1481 /// Declare `n` to belong to the set
1482 fn add(&mut self, n: usize);
1483
1484 /// Declare `n` not to belong to the set
1485 #[allow(unused)]
1486 fn discard(&mut self, n: usize);
1487
1488 /// Replace this bit set by its union with other
1489 fn union(&mut self, other: &Self);
1490
1491 /// Poison the bit set
1492 ///
1493 /// Interpretation up to the caller
1494 fn poison(&mut self);
1495
1496 /// Is the bit set poisoned?
1497 ///
1498 /// Interpretation is up to the caller
1499 fn is_poisoned(&self) -> bool;
1500
1501 /// Is the bit set empty?
1502 fn is_empty(&self) -> bool;
1503
1504 /// return `true` if and only if the bit is the full range `[0, n)`
1505 /// of integers
1506 fn is_full_range(&self, n: usize) -> bool;
1507 }
1508
1509 const U64_POISON: u64 = 1 << 63;
1510 const U8_POISON: u8 = 1 << 7;
1511
1512 impl PoisonableBitSet for u64 {
1513 fn vec_of_empty(_sets_size: usize, vec_len: usize) -> Vec<Self> {
1514 vec![0u64; vec_len]
1515 }
1516
1517 fn size(&self) -> usize {
1518 8
1519 }
1520
1521 fn capacity(&self) -> usize {
1522 63
1523 }
1524
1525 fn add(&mut self, n: usize) {
1526 (*self) |= 1u64 << n;
1527 }
1528
1529 fn discard(&mut self, n: usize) {
1530 (*self) &= u64::MAX - (1u64 << n);
1531 }
1532
1533 fn union(&mut self, other: &Self) {
1534 if *self != *other {
1535 (*self) |= *other;
1536 }
1537 }
1538
1539 fn is_full_range(&self, n: usize) -> bool {
1540 *self + 1 == (1u64 << n)
1541 }
1542
1543 fn is_empty(&self) -> bool {
1544 *self == 0
1545 }
1546
1547 fn poison(&mut self) {
1548 *self = U64_POISON;
1549 }
1550
1551 fn is_poisoned(&self) -> bool {
1552 // equality comparison would be tempting but would not resist
1553 // operations after poisoning (even if these should be bogus).
1554 *self >= U64_POISON
1555 }
1556 }
1557
1558 impl PoisonableBitSet for u8 {
1559 fn vec_of_empty(_sets_size: usize, vec_len: usize) -> Vec<Self> {
1560 vec![0; vec_len]
1561 }
1562
1563 fn size(&self) -> usize {
1564 1
1565 }
1566
1567 fn capacity(&self) -> usize {
1568 7
1569 }
1570
1571 fn add(&mut self, n: usize) {
1572 (*self) |= 1 << n;
1573 }
1574
1575 fn discard(&mut self, n: usize) {
1576 (*self) &= u8::MAX - (1 << n);
1577 }
1578
1579 fn union(&mut self, other: &Self) {
1580 if *self != *other {
1581 (*self) |= *other;
1582 }
1583 }
1584
1585 fn is_full_range(&self, n: usize) -> bool {
1586 *self + 1 == (1 << n)
1587 }
1588
1589 fn is_empty(&self) -> bool {
1590 *self == 0
1591 }
1592
1593 fn poison(&mut self) {
1594 *self = U8_POISON;
1595 }
1596
1597 fn is_poisoned(&self) -> bool {
1598 // equality comparison would be tempting but would not resist
1599 // operations after poisoning (even if these should be bogus).
1600 *self >= U8_POISON
1601 }
1602 }
1603
1604 /// A poisonable bit set whose capacity is not known at compile time but
1605 /// is constant after initial construction
1606 ///
1607 /// This can be way further optimized if performance assessments (speed
1608 /// and/or RAM) require it.
1609 /// As far as RAM is concerned, for large vectors of these, the main problem
1610 /// would be the repetition of set_size in each item. We would need a trait
1611 /// to abstract over the idea of a vector of such bit sets to do better.
1612 #[derive(Clone, PartialEq)]
1613 struct NonStaticPoisonableBitSet {
1614 set_size: usize,
1615 bit_set: Vec<u64>,
1616 }
1617
1618 /// Number of `u64` needed for a [`NonStaticPoisonableBitSet`] of given size
1619 fn non_static_poisonable_inner_len(set_size: usize) -> usize {
1620 1 + (set_size + 1) / 64
1621 }
1622
1623 impl NonStaticPoisonableBitSet {
1624 /// The index of the sub-bit set for the given n, and the index inside
1625 /// the latter
1626 fn index(&self, n: usize) -> (usize, usize) {
1627 (n / 64, n % 64)
1628 }
1629 }
1630
1631 /// Mock implementation to ensure that the trait makes sense
1632 impl PoisonableBitSet for NonStaticPoisonableBitSet {
1633 fn vec_of_empty(set_size: usize, vec_len: usize) -> Vec<Self> {
1634 let tmpl = Self {
1635 set_size,
1636 bit_set: vec![0u64; non_static_poisonable_inner_len(set_size)],
1637 };
1638 vec![tmpl; vec_len]
1639 }
1640
1641 fn size(&self) -> usize {
1642 8 + self.bit_set.len() * 8
1643 }
1644
1645 fn capacity(&self) -> usize {
1646 self.set_size
1647 }
1648
1649 fn add(&mut self, n: usize) {
1650 let (sub_bs, bit_pos) = self.index(n);
1651 self.bit_set[sub_bs] |= 1 << bit_pos
1652 }
1653
1654 fn discard(&mut self, n: usize) {
1655 let (sub_bs, bit_pos) = self.index(n);
1656 self.bit_set[sub_bs] |= u64::MAX - (1 << bit_pos)
1657 }
1658
1659 fn union(&mut self, other: &Self) {
1660 assert!(
1661 self.set_size == other.set_size,
1662 "Binary operations on bit sets can only be done on same size"
1663 );
1664 for i in 0..self.bit_set.len() - 1 {
1665 self.bit_set[i] |= other.bit_set[i]
1666 }
1667 }
1668
1669 fn is_full_range(&self, n: usize) -> bool {
1670 let (sub_bs, bit_pos) = self.index(n);
1671 self.bit_set[..sub_bs].iter().all(|bs| *bs == u64::MAX)
1672 && self.bit_set[sub_bs] == (1 << (bit_pos + 1)) - 1
1673 }
1674
1675 fn is_empty(&self) -> bool {
1676 self.bit_set.iter().all(|bs| *bs == 0u64)
1677 }
1678
1679 fn poison(&mut self) {
1680 let (sub_bs, bit_pos) = self.index(self.set_size);
1681 self.bit_set[sub_bs] = 1 << bit_pos;
1682 }
1683
1684 fn is_poisoned(&self) -> bool {
1685 let (sub_bs, bit_pos) = self.index(self.set_size);
1686 self.bit_set[sub_bs] >= 1 << bit_pos
1687 }
1688 }
1689
1690 /// Set of roots of all non-public phases
1691 pub type RootsPerPhase = [Vec<Revision>; Phase::non_public_phases().len()];
1692
1693 #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
1694 pub enum Phase {
1695 Public = 0,
1696 Draft = 1,
1697 Secret = 2,
1698 Archived = 3,
1699 Internal = 4,
1700 }
1701
1702 impl TryFrom<usize> for Phase {
1703 type Error = RevlogError;
1704
1705 fn try_from(value: usize) -> Result<Self, Self::Error> {
1706 Ok(match value {
1707 0 => Self::Public,
1708 1 => Self::Draft,
1709 2 => Self::Secret,
1710 32 => Self::Archived,
1711 96 => Self::Internal,
1712 v => {
1713 return Err(RevlogError::corrupted(format!(
1714 "invalid phase value {}",
1715 v
1716 )))
1717 }
1718 })
1719 }
1720 }
1721
1722 impl Phase {
1723 pub const fn all_phases() -> &'static [Self] {
1724 &[
1725 Self::Public,
1726 Self::Draft,
1727 Self::Secret,
1728 Self::Archived,
1729 Self::Internal,
1730 ]
1731 }
1732 pub const fn non_public_phases() -> &'static [Self] {
1733 &[Self::Draft, Self::Secret, Self::Archived, Self::Internal]
1734 }
1735 }
1736
1737 fn inline_scan(bytes: &[u8]) -> (usize, Vec<usize>) {
1738 let mut offset: usize = 0;
1739 let mut offsets = Vec::new();
1740
1741 while offset + INDEX_ENTRY_SIZE <= bytes.len() {
1742 offsets.push(offset);
1743 let end = offset + INDEX_ENTRY_SIZE;
1744 let entry = IndexEntry { bytes: &bytes[offset..end] };
1745
1746 offset += INDEX_ENTRY_SIZE + entry.compressed_len() as usize;
1747 }
1748 (offset, offsets)
1749 }
1750
1751 impl super::RevlogIndex for Index {
1752 fn len(&self) -> usize {
1753 self.len()
1754 }
1755
1756 fn node(&self, rev: Revision) -> &Node {
1757 self.get_entry(rev).hash()
1758 }
1759 }
1760
1761 #[derive(Debug, PartialEq, Eq)]
1762 pub struct IndexEntry<'a> {
1763 bytes: &'a [u8],
1764 }
1765
1766 static NULL_ENTRY: &[u8] = &[
1767 0u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255,
1768 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0,
1769 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1770 ];
1771
1772 impl<'a> IndexEntry<'a> {
1773 /// Return the offset of the data.
1774 pub fn offset(&self) -> usize {
1775 let mut bytes = [0; 8];
1776 bytes[2..8].copy_from_slice(&self.bytes[0..=5]);
1777 BigEndian::read_u64(&bytes[..]) as usize
1778 }
1779 pub fn raw_offset(&self) -> u64 {
1780 BigEndian::read_u64(&self.bytes[0..8])
1781 }
1782
1783 pub fn flags(&self) -> u16 {
1784 BigEndian::read_u16(&self.bytes[6..=7])
1785 }
1786
1787 /// Return the compressed length of the data.
1788 pub fn compressed_len(&self) -> u32 {
1789 BigEndian::read_u32(&self.bytes[8..=11])
1790 }
1791
1792 /// Return the uncompressed length of the data.
1793 pub fn uncompressed_len(&self) -> i32 {
1794 BigEndian::read_i32(&self.bytes[12..=15])
1795 }
1796
1797 /// Return the revision upon which the data has been derived.
1798 pub fn base_revision_or_base_of_delta_chain(&self) -> UncheckedRevision {
1799 // TODO Maybe return an Option when base_revision == rev?
1800 // Requires to add rev to IndexEntry
1801
1802 BigEndian::read_i32(&self.bytes[16..]).into()
1803 }
1804
1805 pub fn link_revision(&self) -> UncheckedRevision {
1806 BigEndian::read_i32(&self.bytes[20..]).into()
1807 }
1808
1809 pub fn p1(&self) -> UncheckedRevision {
1810 BigEndian::read_i32(&self.bytes[24..]).into()
1811 }
1812
1813 pub fn p2(&self) -> UncheckedRevision {
1814 BigEndian::read_i32(&self.bytes[28..]).into()
1815 }
1816
1817 /// Return the hash of revision's full text.
1818 ///
1819 /// Currently, SHA-1 is used and only the first 20 bytes of this field
1820 /// are used.
1821 pub fn hash(&self) -> &'a Node {
1822 (&self.bytes[32..52]).try_into().unwrap()
1823 }
1824
1825 pub fn as_bytes(&self) -> &'a [u8] {
1826 self.bytes
1827 }
1828 }
1829
1830 #[cfg(test)]
1831 pub use tests::IndexEntryBuilder;
1832
1833 #[cfg(test)]
1834 mod tests {
1835 use super::*;
1836 use crate::NULL_NODE;
1837
1838 #[cfg(test)]
1839 #[derive(Debug, Copy, Clone)]
1840 pub struct IndexEntryBuilder {
1841 is_first: bool,
1842 is_inline: bool,
1843 is_general_delta: bool,
1844 version: u16,
1845 offset: usize,
1846 compressed_len: usize,
1847 uncompressed_len: usize,
1848 base_revision_or_base_of_delta_chain: Revision,
1849 link_revision: Revision,
1850 p1: Revision,
1851 p2: Revision,
1852 node: Node,
1853 }
1854
1855 #[cfg(test)]
1856 impl IndexEntryBuilder {
1857 #[allow(clippy::new_without_default)]
1858 pub fn new() -> Self {
1859 Self {
1860 is_first: false,
1861 is_inline: false,
1862 is_general_delta: true,
1863 version: 1,
1864 offset: 0,
1865 compressed_len: 0,
1866 uncompressed_len: 0,
1867 base_revision_or_base_of_delta_chain: Revision(0),
1868 link_revision: Revision(0),
1869 p1: NULL_REVISION,
1870 p2: NULL_REVISION,
1871 node: NULL_NODE,
1872 }
1873 }
1874
1875 pub fn is_first(&mut self, value: bool) -> &mut Self {
1876 self.is_first = value;
1877 self
1878 }
1879
1880 pub fn with_inline(&mut self, value: bool) -> &mut Self {
1881 self.is_inline = value;
1882 self
1883 }
1884
1885 pub fn with_general_delta(&mut self, value: bool) -> &mut Self {
1886 self.is_general_delta = value;
1887 self
1888 }
1889
1890 pub fn with_version(&mut self, value: u16) -> &mut Self {
1891 self.version = value;
1892 self
1893 }
1894
1895 pub fn with_offset(&mut self, value: usize) -> &mut Self {
1896 self.offset = value;
1897 self
1898 }
1899
1900 pub fn with_compressed_len(&mut self, value: usize) -> &mut Self {
1901 self.compressed_len = value;
1902 self
1903 }
1904
1905 pub fn with_uncompressed_len(&mut self, value: usize) -> &mut Self {
1906 self.uncompressed_len = value;
1907 self
1908 }
1909
1910 pub fn with_base_revision_or_base_of_delta_chain(
1911 &mut self,
1912 value: Revision,
1913 ) -> &mut Self {
1914 self.base_revision_or_base_of_delta_chain = value;
1915 self
1916 }
1917
1918 pub fn with_link_revision(&mut self, value: Revision) -> &mut Self {
1919 self.link_revision = value;
1920 self
1921 }
1922
1923 pub fn with_p1(&mut self, value: Revision) -> &mut Self {
1924 self.p1 = value;
1925 self
1926 }
1927
1928 pub fn with_p2(&mut self, value: Revision) -> &mut Self {
1929 self.p2 = value;
1930 self
1931 }
1932
1933 pub fn with_node(&mut self, value: Node) -> &mut Self {
1934 self.node = value;
1935 self
1936 }
1937
1938 pub fn build(&self) -> Vec<u8> {
1939 let mut bytes = Vec::with_capacity(INDEX_ENTRY_SIZE);
1940 if self.is_first {
1941 bytes.extend(match (self.is_general_delta, self.is_inline) {
1942 (false, false) => [0u8, 0],
1943 (false, true) => [0u8, 1],
1944 (true, false) => [0u8, 2],
1945 (true, true) => [0u8, 3],
1946 });
1947 bytes.extend(self.version.to_be_bytes());
1948 // Remaining offset bytes.
1949 bytes.extend([0u8; 2]);
1950 } else {
1951 // Offset stored on 48 bits (6 bytes)
1952 bytes.extend(&(self.offset as u64).to_be_bytes()[2..]);
1953 }
1954 bytes.extend([0u8; 2]); // Revision flags.
1955 bytes.extend((self.compressed_len as u32).to_be_bytes());
1956 bytes.extend((self.uncompressed_len as u32).to_be_bytes());
1957 bytes.extend(
1958 self.base_revision_or_base_of_delta_chain.0.to_be_bytes(),
1959 );
1960 bytes.extend(self.link_revision.0.to_be_bytes());
1961 bytes.extend(self.p1.0.to_be_bytes());
1962 bytes.extend(self.p2.0.to_be_bytes());
1963 bytes.extend(self.node.as_bytes());
1964 bytes.extend(vec![0u8; 12]);
1965 bytes
1966 }
1967 }
1968
1969 pub fn is_inline(index_bytes: &[u8]) -> bool {
1970 IndexHeader::parse(index_bytes)
1971 .expect("invalid header")
1972 .format_flags()
1973 .is_inline()
1974 }
1975
1976 pub fn uses_generaldelta(index_bytes: &[u8]) -> bool {
1977 IndexHeader::parse(index_bytes)
1978 .expect("invalid header")
1979 .format_flags()
1980 .uses_generaldelta()
1981 }
1982
1983 pub fn get_version(index_bytes: &[u8]) -> u16 {
1984 IndexHeader::parse(index_bytes)
1985 .expect("invalid header")
1986 .format_version()
1987 }
1988
1989 #[test]
1990 fn flags_when_no_inline_flag_test() {
1991 let bytes = IndexEntryBuilder::new()
1992 .is_first(true)
1993 .with_general_delta(false)
1994 .with_inline(false)
1995 .build();
1996
1997 assert!(!is_inline(&bytes));
1998 assert!(!uses_generaldelta(&bytes));
1999 }
2000
2001 #[test]
2002 fn flags_when_inline_flag_test() {
2003 let bytes = IndexEntryBuilder::new()
2004 .is_first(true)
2005 .with_general_delta(false)
2006 .with_inline(true)
2007 .build();
2008
2009 assert!(is_inline(&bytes));
2010 assert!(!uses_generaldelta(&bytes));
2011 }
2012
2013 #[test]
2014 fn flags_when_inline_and_generaldelta_flags_test() {
2015 let bytes = IndexEntryBuilder::new()
2016 .is_first(true)
2017 .with_general_delta(true)
2018 .with_inline(true)
2019 .build();
2020
2021 assert!(is_inline(&bytes));
2022 assert!(uses_generaldelta(&bytes));
2023 }
2024
2025 #[test]
2026 fn test_offset() {
2027 let bytes = IndexEntryBuilder::new().with_offset(1).build();
2028 let entry = IndexEntry { bytes: &bytes };
2029
2030 assert_eq!(entry.offset(), 1)
2031 }
2032
2033 #[test]
2034 fn test_compressed_len() {
2035 let bytes = IndexEntryBuilder::new().with_compressed_len(1).build();
2036 let entry = IndexEntry { bytes: &bytes };
2037
2038 assert_eq!(entry.compressed_len(), 1)
2039 }
2040
2041 #[test]
2042 fn test_uncompressed_len() {
2043 let bytes = IndexEntryBuilder::new().with_uncompressed_len(1).build();
2044 let entry = IndexEntry { bytes: &bytes };
2045
2046 assert_eq!(entry.uncompressed_len(), 1)
2047 }
2048
2049 #[test]
2050 fn test_base_revision_or_base_of_delta_chain() {
2051 let bytes = IndexEntryBuilder::new()
2052 .with_base_revision_or_base_of_delta_chain(Revision(1))
2053 .build();
2054 let entry = IndexEntry { bytes: &bytes };
2055
2056 assert_eq!(entry.base_revision_or_base_of_delta_chain(), 1.into())
2057 }
2058
2059 #[test]
2060 fn link_revision_test() {
2061 let bytes =
2062 IndexEntryBuilder::new().with_link_revision(Revision(123)).build();
2063
2064 let entry = IndexEntry { bytes: &bytes };
2065
2066 assert_eq!(entry.link_revision(), 123.into());
2067 }
2068
2069 #[test]
2070 fn p1_test() {
2071 let bytes = IndexEntryBuilder::new().with_p1(Revision(123)).build();
2072
2073 let entry = IndexEntry { bytes: &bytes };
2074
2075 assert_eq!(entry.p1(), 123.into());
2076 }
2077
2078 #[test]
2079 fn p2_test() {
2080 let bytes = IndexEntryBuilder::new().with_p2(Revision(123)).build();
2081
2082 let entry = IndexEntry { bytes: &bytes };
2083
2084 assert_eq!(entry.p2(), 123.into());
2085 }
2086
2087 #[test]
2088 fn node_test() {
2089 let node =
2090 Node::from_hex("0123456789012345678901234567890123456789").unwrap();
2091 let bytes = IndexEntryBuilder::new().with_node(node).build();
2092
2093 let entry = IndexEntry { bytes: &bytes };
2094
2095 assert_eq!(*entry.hash(), node);
2096 }
2097
2098 #[test]
2099 fn version_test() {
2100 let bytes =
2101 IndexEntryBuilder::new().is_first(true).with_version(2).build();
2102
2103 assert_eq!(get_version(&bytes), 2)
2104 }
2105 }