Debian Codegraph @

lib/src/default_index/rev_walk.rs

raw
1 // Copyright 2023 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::cmp::Reverse;
16 use std::cmp::max;
17 use std::collections::HashMap;
18 use std::collections::HashSet;
19 use std::iter::Fuse;
20 use std::iter::FusedIterator;
21 use std::ops::Range;
22
23 use smallvec::SmallVec;
24
25 use super::composite::CompositeCommitIndex;
26 use super::composite::CompositeIndex;
27 use super::entry::GlobalCommitPosition;
28 use super::entry::SmallGlobalCommitPositionsVec;
29 use super::rev_walk_queue::RevWalkQueue;
30 use super::rev_walk_queue::RevWalkWorkItem;
31 use crate::revset::PARENTS_RANGE_FULL;
32
33 /// Like `Iterator`, but doesn't borrow the `index` internally.
34 pub(super) trait RevWalk<I: ?Sized> {
35 type Item;
36
37 /// Advances the iteration and returns the next item.
38 ///
39 /// The caller must provide the same `index` instance.
40 ///
41 /// Returns `None` when the iteration is finished. Once `None` is returned,
42 /// this will never resume. In other words, a `RevWalk` is fused.
43 fn next(&mut self, index: &I) -> Option<Self::Item>;
44
45 // The following methods are provided for convenience. They are not supposed
46 // to be reimplemented.
47
48 /// Wraps in adapter that will filter and transform items by the given
49 /// function.
50 fn filter_map<B, F>(self, f: F) -> FilterMapRevWalk<Self, F>
51 where
52 Self: Sized,
53 F: FnMut(&I, Self::Item) -> Option<B>,
54 {
55 FilterMapRevWalk { walk: self, f }
56 }
57
58 /// Wraps in adapter that will transform items by the given function.
59 fn map<B, F>(self, f: F) -> MapRevWalk<Self, F>
60 where
61 Self: Sized,
62 F: FnMut(&I, Self::Item) -> B,
63 {
64 MapRevWalk { walk: self, f }
65 }
66
67 /// Wraps in adapter that can peek one more item without consuming.
68 fn peekable(self) -> PeekableRevWalk<I, Self>
69 where
70 Self: Sized,
71 {
72 PeekableRevWalk {
73 walk: self,
74 peeked: None,
75 }
76 }
77
78 /// Reattaches the underlying `index`.
79 fn attach(self, index: &I) -> RevWalkBorrowedIndexIter<'_, I, Self>
80 where
81 Self: Sized,
82 {
83 RevWalkBorrowedIndexIter { index, walk: self }
84 }
85 }
86
87 impl<I: ?Sized, W: RevWalk<I> + ?Sized> RevWalk<I> for Box<W> {
88 type Item = W::Item;
89
90 fn next(&mut self, index: &I) -> Option<Self::Item> {
91 <W as RevWalk<I>>::next(self, index)
92 }
93 }
94
95 /// Adapter that turns `Iterator` into `RevWalk` by dropping index argument.
96 ///
97 /// As the name suggests, the source object is usually a slice or `Vec`.
98 #[derive(Clone, Debug)]
99 pub(super) struct EagerRevWalk<T> {
100 iter: Fuse<T>,
101 }
102
103 impl<T: Iterator> EagerRevWalk<T> {
104 pub fn new(iter: T) -> Self {
105 Self { iter: iter.fuse() }
106 }
107 }
108
109 impl<I: ?Sized, T: Iterator> RevWalk<I> for EagerRevWalk<T> {
110 type Item = T::Item;
111
112 fn next(&mut self, _index: &I) -> Option<Self::Item> {
113 self.iter.next()
114 }
115 }
116
117 #[derive(Clone, Debug)]
118 #[must_use]
119 pub(super) struct FilterMapRevWalk<W, F> {
120 walk: W,
121 f: F,
122 }
123
124 impl<B, I, W, F> RevWalk<I> for FilterMapRevWalk<W, F>
125 where
126 I: ?Sized,
127 W: RevWalk<I>,
128 F: FnMut(&I, W::Item) -> Option<B>,
129 {
130 type Item = B;
131
132 fn next(&mut self, index: &I) -> Option<Self::Item> {
133 while let Some(item) = self.walk.next(index) {
134 if let Some(new_item) = (self.f)(index, item) {
135 return Some(new_item);
136 }
137 }
138 None
139 }
140 }
141
142 #[derive(Clone, Debug)]
143 #[must_use]
144 pub(super) struct MapRevWalk<W, F> {
145 walk: W,
146 f: F,
147 }
148
149 impl<B, I, W, F> RevWalk<I> for MapRevWalk<W, F>
150 where
151 I: ?Sized,
152 W: RevWalk<I>,
153 F: FnMut(&I, W::Item) -> B,
154 {
155 type Item = B;
156
157 fn next(&mut self, index: &I) -> Option<Self::Item> {
158 self.walk.next(index).map(|item| (self.f)(index, item))
159 }
160 }
161
162 #[derive(Clone, Debug)]
163 #[must_use]
164 pub(super) struct PeekableRevWalk<I: ?Sized, W: RevWalk<I>> {
165 walk: W,
166 // Since RevWalk is fused, we don't need a nested Option<Option<_>>.
167 peeked: Option<W::Item>,
168 }
169
170 impl<I: ?Sized, W: RevWalk<I>> PeekableRevWalk<I, W> {
171 pub fn peek(&mut self, index: &I) -> Option<&W::Item> {
172 if self.peeked.is_none() {
173 self.peeked = self.walk.next(index);
174 }
175 self.peeked.as_ref()
176 }
177
178 pub fn next_if(
179 &mut self,
180 index: &I,
181 predicate: impl FnOnce(&W::Item) -> bool,
182 ) -> Option<W::Item> {
183 match self.next(index) {
184 Some(item) if predicate(&item) => Some(item),
185 other => {
186 assert!(self.peeked.is_none());
187 self.peeked = other;
188 None
189 }
190 }
191 }
192 }
193
194 impl<I: ?Sized, W: RevWalk<I>> RevWalk<I> for PeekableRevWalk<I, W> {
195 type Item = W::Item;
196
197 fn next(&mut self, index: &I) -> Option<Self::Item> {
198 self.peeked.take().or_else(|| self.walk.next(index))
199 }
200 }
201
202 /// Adapter that turns `RevWalk` into `Iterator` by attaching borrowed `index`.
203 #[derive(Clone, Debug)]
204 #[must_use]
205 pub(super) struct RevWalkBorrowedIndexIter<'a, I: ?Sized, W> {
206 index: &'a I,
207 walk: W,
208 }
209
210 impl<I: ?Sized, W> RevWalkBorrowedIndexIter<'_, I, W> {
211 /// Turns into `'static`-lifetime walk object by detaching the index.
212 pub fn detach(self) -> W {
213 self.walk
214 }
215 }
216
217 impl<I: ?Sized, W: RevWalk<I>> Iterator for RevWalkBorrowedIndexIter<'_, I, W> {
218 type Item = W::Item;
219
220 fn next(&mut self) -> Option<Self::Item> {
221 self.walk.next(self.index)
222 }
223 }
224
225 impl<I: ?Sized, W: RevWalk<I>> FusedIterator for RevWalkBorrowedIndexIter<'_, I, W> {}
226
227 /// Adapter that turns `RevWalk` into `Iterator` by attaching owned `index`.
228 #[derive(Clone, Debug)]
229 #[must_use]
230 pub(super) struct RevWalkOwnedIndexIter<I, W> {
231 index: I,
232 walk: W,
233 }
234
235 impl<I, W: RevWalk<I>> Iterator for RevWalkOwnedIndexIter<I, W> {
236 type Item = W::Item;
237
238 fn next(&mut self) -> Option<Self::Item> {
239 self.walk.next(&self.index)
240 }
241 }
242
243 impl<I, W: RevWalk<I>> FusedIterator for RevWalkOwnedIndexIter<I, W> {}
244
245 pub(super) trait RevWalkIndex {
246 type Position: Copy + Ord;
247 type AdjacentPositions: IntoIterator<Item = Self::Position> + AsRef<[Self::Position]>;
248
249 fn adjacent_positions(&self, pos: Self::Position) -> Self::AdjacentPositions;
250 }
251
252 impl RevWalkIndex for CompositeIndex {
253 type Position = GlobalCommitPosition;
254 type AdjacentPositions = SmallGlobalCommitPositionsVec;
255
256 fn adjacent_positions(&self, pos: Self::Position) -> Self::AdjacentPositions {
257 self.commits().entry_by_pos(pos).parent_positions()
258 }
259 }
260
261 #[derive(Clone)]
262 pub(super) struct RevWalkDescendantsIndex {
263 children_map: HashMap<GlobalCommitPosition, DescendantIndexPositionsVec>,
264 }
265
266 // See SmallGlobalCommitPositionsVec for the array size.
267 type DescendantIndexPositionsVec = SmallVec<[Reverse<GlobalCommitPosition>; 4]>;
268
269 impl RevWalkDescendantsIndex {
270 fn build(
271 index: &CompositeCommitIndex,
272 positions: impl IntoIterator<Item = GlobalCommitPosition>,
273 ) -> Self {
274 // For dense set, it's probably cheaper to use `Vec` instead of `HashMap`.
275 let mut children_map: HashMap<GlobalCommitPosition, DescendantIndexPositionsVec> =
276 HashMap::new();
277 for pos in positions {
278 children_map.entry(pos).or_default(); // mark head node
279 for parent_pos in index.entry_by_pos(pos).parent_positions() {
280 let parent = children_map.entry(parent_pos).or_default();
281 parent.push(Reverse(pos));
282 }
283 }
284
285 Self { children_map }
286 }
287
288 fn contains_pos(&self, pos: GlobalCommitPosition) -> bool {
289 self.children_map.contains_key(&pos)
290 }
291 }
292
293 impl RevWalkIndex for RevWalkDescendantsIndex {
294 type Position = Reverse<GlobalCommitPosition>;
295 type AdjacentPositions = DescendantIndexPositionsVec;
296
297 fn adjacent_positions(&self, pos: Self::Position) -> Self::AdjacentPositions {
298 self.children_map[&pos.0].clone()
299 }
300 }
301
302 #[derive(Clone)]
303 #[must_use]
304 pub(super) struct RevWalkBuilder<'a> {
305 index: &'a CompositeIndex,
306 wanted: Vec<GlobalCommitPosition>,
307 unwanted: Vec<GlobalCommitPosition>,
308 wanted_parents_range: Range<u32>,
309 }
310
311 impl<'a> RevWalkBuilder<'a> {
312 pub fn new(index: &'a CompositeIndex) -> Self {
313 Self {
314 index,
315 wanted: Vec::new(),
316 unwanted: Vec::new(),
317 wanted_parents_range: PARENTS_RANGE_FULL,
318 }
319 }
320
321 /// Sets head positions to be included.
322 pub fn wanted_heads(mut self, positions: Vec<GlobalCommitPosition>) -> Self {
323 self.wanted = positions;
324 self
325 }
326
327 /// Sets range of parents to iterate over for wanted heads.
328 pub fn wanted_parents_range(mut self, wanted_parents_range: Range<u32>) -> Self {
329 assert!(wanted_parents_range.start <= wanted_parents_range.end);
330 self.wanted_parents_range = wanted_parents_range;
331 self
332 }
333
334 /// Sets root positions to be excluded. The roots precede the heads.
335 pub fn unwanted_roots(mut self, positions: Vec<GlobalCommitPosition>) -> Self {
336 self.unwanted = positions;
337 self
338 }
339
340 /// Walks ancestors.
341 pub fn ancestors(self) -> RevWalkAncestors<'a> {
342 self.ancestors_with_min_pos(GlobalCommitPosition::MIN)
343 }
344
345 fn ancestors_with_min_pos(self, min_pos: GlobalCommitPosition) -> RevWalkAncestors<'a> {
346 let index = self.index;
347 let wanted_parents_range = self.wanted_parents_range;
348 let mut wanted_queue = RevWalkQueue::with_min_pos(min_pos);
349 let mut unwanted_queue = RevWalkQueue::with_min_pos(min_pos);
350 wanted_queue.extend(self.wanted, ());
351 unwanted_queue.extend(self.unwanted, ());
352 RevWalkBorrowedIndexIter {
353 index,
354 walk: RevWalkImpl {
355 wanted_queue,
356 unwanted_queue,
357 wanted_parents_range,
358 },
359 }
360 }
361
362 /// Walks ancestors within the `generation_range`.
363 ///
364 /// A generation number counts from the heads.
365 pub fn ancestors_filtered_by_generation(
366 self,
367 generation_range: Range<u32>,
368 ) -> RevWalkAncestorsGenerationRange<'a> {
369 let index = self.index;
370 let wanted_parents_range = self.wanted_parents_range;
371 let mut wanted_queue = RevWalkQueue::with_min_pos(GlobalCommitPosition::MIN);
372 let mut unwanted_queue = RevWalkQueue::with_min_pos(GlobalCommitPosition::MIN);
373 let item_range = RevWalkItemGenerationRange::from_filter_range(generation_range.clone());
374 wanted_queue.extend(self.wanted, Reverse(item_range));
375 unwanted_queue.extend(self.unwanted, ());
376 RevWalkBorrowedIndexIter {
377 index,
378 walk: RevWalkGenerationRangeImpl {
379 wanted_queue,
380 unwanted_queue,
381 wanted_parents_range,
382 generation_end: generation_range.end,
383 },
384 }
385 }
386
387 /// Walks ancestors until all of the reachable roots in `root_positions` get
388 /// visited.
389 ///
390 /// Use this if you are only interested in descendants of the given roots.
391 /// The caller still needs to filter out unwanted entries.
392 pub fn ancestors_until_roots(
393 self,
394 root_positions: impl IntoIterator<Item = GlobalCommitPosition>,
395 ) -> RevWalkAncestors<'a> {
396 // We can also make it stop visiting based on the generation number. Maybe
397 // it will perform better for unbalanced branchy history.
398 // https://github.com/jj-vcs/jj/pull/1492#discussion_r1160678325
399 let min_pos = root_positions
400 .into_iter()
401 .min()
402 .unwrap_or(GlobalCommitPosition::MAX);
403 self.ancestors_with_min_pos(min_pos)
404 }
405
406 /// Fully consumes ancestors and walks back from the `root_positions`.
407 ///
408 /// The returned iterator yields entries in order of ascending index
409 /// position.
410 pub fn descendants(
411 self,
412 root_positions: HashSet<GlobalCommitPosition>,
413 ) -> RevWalkDescendants<'a> {
414 let index = self.index;
415 let candidate_positions = self
416 .ancestors_until_roots(root_positions.iter().copied())
417 .collect();
418 RevWalkBorrowedIndexIter {
419 index,
420 walk: RevWalkDescendantsImpl {
421 candidate_positions,
422 root_positions,
423 reachable_positions: HashSet::new(),
424 },
425 }
426 }
427
428 /// Fully consumes ancestors and walks back from the `root_positions` within
429 /// the `generation_range`.
430 ///
431 /// A generation number counts from the roots.
432 ///
433 /// The returned iterator yields entries in order of ascending index
434 /// position.
435 pub fn descendants_filtered_by_generation(
436 self,
437 root_positions: Vec<GlobalCommitPosition>,
438 generation_range: Range<u32>,
439 ) -> RevWalkDescendantsGenerationRange {
440 let index = self.index;
441 let positions = self.ancestors_until_roots(root_positions.iter().copied());
442 let descendants_index = RevWalkDescendantsIndex::build(index.commits(), positions);
443
444 let mut wanted_queue = RevWalkQueue::with_min_pos(Reverse(GlobalCommitPosition::MAX));
445 let unwanted_queue = RevWalkQueue::with_min_pos(Reverse(GlobalCommitPosition::MAX));
446 let item_range = RevWalkItemGenerationRange::from_filter_range(generation_range.clone());
447 for pos in root_positions {
448 // Do not add unreachable roots which shouldn't be visited
449 if descendants_index.contains_pos(pos) {
450 wanted_queue.push(Reverse(pos), Reverse(item_range));
451 }
452 }
453 RevWalkOwnedIndexIter {
454 index: descendants_index,
455 walk: RevWalkGenerationRangeImpl {
456 wanted_queue,
457 unwanted_queue,
458 // Since we're using the descendants index, this actually is a range for the
459 // children instead of the parents.
460 wanted_parents_range: PARENTS_RANGE_FULL,
461 generation_end: generation_range.end,
462 },
463 }
464 }
465 }
466
467 pub(super) type RevWalkAncestors<'a> =
468 RevWalkBorrowedIndexIter<'a, CompositeIndex, RevWalkImpl<GlobalCommitPosition>>;
469
470 #[derive(Clone)]
471 #[must_use]
472 pub(super) struct RevWalkImpl<P> {
473 wanted_queue: RevWalkQueue<P, ()>,
474 unwanted_queue: RevWalkQueue<P, ()>,
475 wanted_parents_range: Range<u32>,
476 }
477
478 impl<I: RevWalkIndex + ?Sized> RevWalk<I> for RevWalkImpl<I::Position> {
479 type Item = I::Position;
480
481 fn next(&mut self, index: &I) -> Option<Self::Item> {
482 while let Some(item) = self.wanted_queue.pop() {
483 self.wanted_queue.skip_while_eq(&item.pos);
484 if flush_queue_until(&mut self.unwanted_queue, index, item.pos).is_some() {
485 continue;
486 }
487 let parents = index.adjacent_positions(item.pos);
488 self.wanted_queue.extend(
489 filter_slice_by_range(parents.as_ref(), &self.wanted_parents_range)
490 .iter()
491 .copied(),
492 (),
493 );
494 return Some(item.pos);
495 }
496 None
497 }
498 }
499
500 pub(super) type RevWalkAncestorsGenerationRange<'a> =
501 RevWalkBorrowedIndexIter<'a, CompositeIndex, RevWalkGenerationRangeImpl<GlobalCommitPosition>>;
502 pub(super) type RevWalkDescendantsGenerationRange = RevWalkOwnedIndexIter<
503 RevWalkDescendantsIndex,
504 RevWalkGenerationRangeImpl<Reverse<GlobalCommitPosition>>,
505 >;
506
507 #[derive(Clone)]
508 #[must_use]
509 pub(super) struct RevWalkGenerationRangeImpl<P> {
510 // Sort item generations in ascending order
511 wanted_queue: RevWalkQueue<P, Reverse<RevWalkItemGenerationRange>>,
512 unwanted_queue: RevWalkQueue<P, ()>,
513 wanted_parents_range: Range<u32>,
514 generation_end: u32,
515 }
516
517 impl<P: Copy + Ord> RevWalkGenerationRangeImpl<P> {
518 fn enqueue_wanted_adjacents<I>(
519 &mut self,
520 index: &I,
521 pos: P,
522 generation: RevWalkItemGenerationRange,
523 ) where
524 I: RevWalkIndex<Position = P> + ?Sized,
525 {
526 // `gen.start` is incremented from 0, which should never overflow
527 if generation.start + 1 >= self.generation_end {
528 return;
529 }
530 let succ_generation = RevWalkItemGenerationRange {
531 start: generation.start + 1,
532 end: generation.end.saturating_add(1),
533 };
534 let parents = index.adjacent_positions(pos);
535 self.wanted_queue.extend(
536 filter_slice_by_range(parents.as_ref(), &self.wanted_parents_range)
537 .iter()
538 .copied(),
539 Reverse(succ_generation),
540 );
541 }
542 }
543
544 impl<I: RevWalkIndex + ?Sized> RevWalk<I> for RevWalkGenerationRangeImpl<I::Position> {
545 type Item = I::Position;
546
547 fn next(&mut self, index: &I) -> Option<Self::Item> {
548 while let Some(item) = self.wanted_queue.pop() {
549 if flush_queue_until(&mut self.unwanted_queue, index, item.pos).is_some() {
550 self.wanted_queue.skip_while_eq(&item.pos);
551 continue;
552 }
553 let Reverse(mut pending_gen) = item.value;
554 let mut some_in_range = pending_gen.contains_end(self.generation_end);
555 while let Some(x) = self.wanted_queue.pop_eq(&item.pos) {
556 // Merge overlapped ranges to reduce number of the queued items.
557 // For queries like `:(heads-)`, `gen.end` is close to `u32::MAX`, so
558 // ranges can be merged into one. If this is still slow, maybe we can add
559 // special case for upper/lower bounded ranges.
560 let Reverse(generation) = x.value;
561 some_in_range |= generation.contains_end(self.generation_end);
562 pending_gen = if let Some(merged) = pending_gen.try_merge_end(generation) {
563 merged
564 } else {
565 self.enqueue_wanted_adjacents(index, item.pos, pending_gen);
566 generation
567 };
568 }
569 self.enqueue_wanted_adjacents(index, item.pos, pending_gen);
570 if some_in_range {
571 return Some(item.pos);
572 }
573 }
574 None
575 }
576 }
577
578 #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
579 struct RevWalkItemGenerationRange {
580 start: u32,
581 end: u32,
582 }
583
584 impl RevWalkItemGenerationRange {
585 /// Translates filter range to item range so that overlapped ranges can be
586 /// merged later.
587 ///
588 /// Example: `generation_range = 1..4`
589 /// ```text
590 /// (original) (translated)
591 /// 0 1 2 3 4 0 1 2 3 4
592 /// *=====o generation_range + generation_end
593 /// + : : item's generation o=====* : item's range
594 /// ```
595 fn from_filter_range(range: Range<u32>) -> Self {
596 Self {
597 start: 0,
598 end: u32::saturating_sub(range.end, range.start),
599 }
600 }
601
602 /// Suppose sorted ranges `self, other`, merges them if overlapped.
603 #[must_use]
604 fn try_merge_end(self, other: Self) -> Option<Self> {
605 (other.start <= self.end).then(|| Self {
606 start: self.start,
607 end: max(self.end, other.end),
608 })
609 }
610
611 #[must_use]
612 fn contains_end(self, end: u32) -> bool {
613 self.start < end && end <= self.end
614 }
615 }
616
617 /// Walks queue items until `bottom_pos`. Returns item if found at `bottom_pos`.
618 fn flush_queue_until<I: RevWalkIndex + ?Sized>(
619 queue: &mut RevWalkQueue<I::Position, ()>,
620 index: &I,
621 bottom_pos: I::Position,
622 ) -> Option<RevWalkWorkItem<I::Position, ()>> {
623 while let Some(item) = queue.pop_if(|x| x.pos >= bottom_pos) {
624 queue.skip_while_eq(&item.pos);
625 queue.extend(index.adjacent_positions(item.pos), ());
626 if item.pos == bottom_pos {
627 return Some(item);
628 }
629 }
630 None
631 }
632
633 /// Walks descendants from the roots, in order of ascending index position.
634 pub(super) type RevWalkDescendants<'a> =
635 RevWalkBorrowedIndexIter<'a, CompositeIndex, RevWalkDescendantsImpl>;
636
637 #[derive(Clone)]
638 #[must_use]
639 pub(super) struct RevWalkDescendantsImpl {
640 candidate_positions: Vec<GlobalCommitPosition>,
641 root_positions: HashSet<GlobalCommitPosition>,
642 reachable_positions: HashSet<GlobalCommitPosition>,
643 }
644
645 impl RevWalkDescendants<'_> {
646 /// Builds a set of index positions reachable from the roots.
647 ///
648 /// This is equivalent to `.collect()` on the new iterator, but returns the
649 /// internal buffer instead.
650 pub fn collect_positions_set(mut self) -> HashSet<GlobalCommitPosition> {
651 self.by_ref().for_each(drop);
652 self.walk.reachable_positions
653 }
654 }
655
656 impl RevWalk<CompositeIndex> for RevWalkDescendantsImpl {
657 type Item = GlobalCommitPosition;
658
659 fn next(&mut self, index: &CompositeIndex) -> Option<Self::Item> {
660 let index = index.commits();
661 while let Some(candidate_pos) = self.candidate_positions.pop() {
662 if self.root_positions.contains(&candidate_pos)
663 || index
664 .entry_by_pos(candidate_pos)
665 .parent_positions()
666 .iter()
667 .any(|parent_pos| self.reachable_positions.contains(parent_pos))
668 {
669 self.reachable_positions.insert(candidate_pos);
670 return Some(candidate_pos);
671 }
672 }
673 None
674 }
675 }
676
677 /// Filter a slice by a range, clamping the range to the length of the slice.
678 pub(super) fn filter_slice_by_range<'a, T: Copy>(slice: &'a [T], range: &Range<u32>) -> &'a [T] {
679 let start = (range.start as usize).min(slice.len());
680 let end = (range.end as usize).min(slice.len());
681 &slice[start..end]
682 }
683
684 #[cfg(test)]
685 #[rustversion::attr(
686 since(1.89),
687 expect(clippy::cloned_ref_to_slice_refs, reason = "makes tests more readable")
688 )]
689 mod tests {
690 use itertools::Itertools as _;
691
692 use super::super::composite::AsCompositeIndex as _;
693 use super::super::mutable::DefaultMutableIndex;
694 use super::*;
695 use crate::backend::ChangeId;
696 use crate::backend::CommitId;
697 use crate::default_index::readonly::FieldLengths;
698
699 const TEST_FIELD_LENGTHS: FieldLengths = FieldLengths {
700 // TODO: align with commit_id_generator()?
701 commit_id: 3,
702 change_id: 16,
703 };
704
705 /// Generator of unique 16-byte ChangeId excluding root id
706 fn change_id_generator() -> impl FnMut() -> ChangeId {
707 let mut iter = (1_u128..).map(|n| ChangeId::new(n.to_le_bytes().into()));
708 move || iter.next().unwrap()
709 }
710
711 fn to_positions_vec(
712 index: &CompositeIndex,
713 commit_ids: &[CommitId],
714 ) -> Vec<GlobalCommitPosition> {
715 commit_ids
716 .iter()
717 .map(|id| index.commits().commit_id_to_pos(id).unwrap())
718 .collect()
719 }
720
721 #[test]
722 fn test_filter_map_rev_walk() {
723 let source = EagerRevWalk::new(vec![0, 1, 2, 3, 4].into_iter());
724 let mut filtered = source.filter_map(|_, v| (v & 1 == 0).then_some(v + 5));
725 assert_eq!(filtered.next(&()), Some(5));
726 assert_eq!(filtered.next(&()), Some(7));
727 assert_eq!(filtered.next(&()), Some(9));
728 assert_eq!(filtered.next(&()), None);
729 assert_eq!(filtered.next(&()), None);
730 }
731
732 #[test]
733 fn test_map_rev_walk() {
734 let source = EagerRevWalk::new(vec![0, 1, 2].into_iter());
735 let mut mapped = source.map(|_, v| v + 5);
736 assert_eq!(mapped.next(&()), Some(5));
737 assert_eq!(mapped.next(&()), Some(6));
738 assert_eq!(mapped.next(&()), Some(7));
739 assert_eq!(mapped.next(&()), None);
740 assert_eq!(mapped.next(&()), None);
741 }
742
743 #[test]
744 fn test_peekable_rev_walk() {
745 let source = EagerRevWalk::new(vec![0, 1, 2, 3].into_iter());
746 let mut peekable = source.peekable();
747 assert_eq!(peekable.peek(&()), Some(&0));
748 assert_eq!(peekable.peek(&()), Some(&0));
749 assert_eq!(peekable.next(&()), Some(0));
750 assert_eq!(peekable.peeked, None);
751 assert_eq!(peekable.next_if(&(), |&v| v == 2), None);
752 assert_eq!(peekable.next(&()), Some(1));
753 assert_eq!(peekable.next_if(&(), |&v| v == 2), Some(2));
754 assert_eq!(peekable.peeked, None);
755 assert_eq!(peekable.peek(&()), Some(&3));
756 assert_eq!(peekable.next_if(&(), |&v| v == 3), Some(3));
757 assert_eq!(peekable.peeked, None);
758 assert_eq!(peekable.next(&()), None);
759 assert_eq!(peekable.next(&()), None);
760
761 let source = EagerRevWalk::new((vec![] as Vec<i32>).into_iter());
762 let mut peekable = source.peekable();
763 assert_eq!(peekable.peek(&()), None);
764 assert_eq!(peekable.next(&()), None);
765 }
766
767 #[test]
768 fn test_walk_ancestors() {
769 let mut new_change_id = change_id_generator();
770 let mut index = DefaultMutableIndex::full(TEST_FIELD_LENGTHS);
771 // 5
772 // |\
773 // 4 | 3
774 // | |/
775 // 1 2
776 // |/
777 // 0
778 let id_0 = CommitId::from_hex("000000");
779 let id_1 = CommitId::from_hex("111111");
780 let id_2 = CommitId::from_hex("222222");
781 let id_3 = CommitId::from_hex("333333");
782 let id_4 = CommitId::from_hex("444444");
783 let id_5 = CommitId::from_hex("555555");
784 index.add_commit_data(id_0.clone(), new_change_id(), &[]);
785 index.add_commit_data(id_1.clone(), new_change_id(), &[id_0.clone()]);
786 index.add_commit_data(id_2.clone(), new_change_id(), &[id_0.clone()]);
787 index.add_commit_data(id_3.clone(), new_change_id(), &[id_2.clone()]);
788 index.add_commit_data(id_4.clone(), new_change_id(), &[id_1.clone()]);
789 index.add_commit_data(id_5.clone(), new_change_id(), &[id_4.clone(), id_2.clone()]);
790
791 let walk_commit_ids = |wanted: &[CommitId], unwanted: &[CommitId]| {
792 let index = index.as_composite();
793 RevWalkBuilder::new(index)
794 .wanted_heads(to_positions_vec(index, wanted))
795 .unwanted_roots(to_positions_vec(index, unwanted))
796 .ancestors()
797 .map(|pos| index.commits().entry_by_pos(pos).commit_id())
798 .collect_vec()
799 };
800
801 // No wanted commits
802 assert!(walk_commit_ids(&[], &[]).is_empty());
803 // Simple linear walk to roo
804 assert_eq!(
805 walk_commit_ids(&[id_4.clone()], &[]),
806 vec![id_4.clone(), id_1.clone(), id_0.clone()]
807 );
808 // Commits that are both wanted and unwanted are not walked
809 assert_eq!(walk_commit_ids(&[id_0.clone()], &[id_0.clone()]), vec![]);
810 // Commits that are listed twice are only walked once
811 assert_eq!(
812 walk_commit_ids(&[id_0.clone(), id_0.clone()], &[]),
813 vec![id_0.clone()]
814 );
815 // If a commit and its ancestor are both wanted, the ancestor still gets walked
816 // only once
817 assert_eq!(
818 walk_commit_ids(&[id_0.clone(), id_1.clone()], &[]),
819 vec![id_1.clone(), id_0.clone()]
820 );
821 // Ancestors of both wanted and unwanted commits are not walked
822 assert_eq!(
823 walk_commit_ids(&[id_2.clone()], &[id_1.clone()]),
824 vec![id_2.clone()]
825 );
826 // Same as above, but the opposite order, to make sure that order in index
827 // doesn't matter
828 assert_eq!(
829 walk_commit_ids(&[id_1.clone()], &[id_2.clone()]),
830 vec![id_1.clone()]
831 );
832 // Two wanted nodes
833 assert_eq!(
834 walk_commit_ids(&[id_1.clone(), id_2.clone()], &[]),
835 vec![id_2.clone(), id_1.clone(), id_0.clone()]
836 );
837 // Order of output doesn't depend on order of input
838 assert_eq!(
839 walk_commit_ids(&[id_2.clone(), id_1.clone()], &[]),
840 vec![id_2.clone(), id_1.clone(), id_0]
841 );
842 // Two wanted nodes that share an unwanted ancestor
843 assert_eq!(
844 walk_commit_ids(&[id_5.clone(), id_3.clone()], &[id_2]),
845 vec![id_5, id_4, id_3, id_1]
846 );
847 }
848
849 #[test]
850 fn test_walk_ancestors_until_roots() {
851 let mut new_change_id = change_id_generator();
852 let mut index = DefaultMutableIndex::full(TEST_FIELD_LENGTHS);
853 // 7
854 // 6 |
855 // 5 |
856 // 4 |
857 // | 3
858 // | 2
859 // |/
860 // 1
861 // 0
862 let id_0 = CommitId::from_hex("000000");
863 let id_1 = CommitId::from_hex("111111");
864 let id_2 = CommitId::from_hex("222222");
865 let id_3 = CommitId::from_hex("333333");
866 let id_4 = CommitId::from_hex("444444");
867 let id_5 = CommitId::from_hex("555555");
868 let id_6 = CommitId::from_hex("666666");
869 let id_7 = CommitId::from_hex("777777");
870 index.add_commit_data(id_0.clone(), new_change_id(), &[]);
871 index.add_commit_data(id_1.clone(), new_change_id(), &[id_0.clone()]);
872 index.add_commit_data(id_2.clone(), new_change_id(), &[id_1.clone()]);
873 index.add_commit_data(id_3.clone(), new_change_id(), &[id_2.clone()]);
874 index.add_commit_data(id_4.clone(), new_change_id(), &[id_1.clone()]);
875 index.add_commit_data(id_5.clone(), new_change_id(), &[id_4.clone()]);
876 index.add_commit_data(id_6.clone(), new_change_id(), &[id_5.clone()]);
877 index.add_commit_data(id_7.clone(), new_change_id(), &[id_3.clone()]);
878
879 let index = index.as_composite();
880 let make_iter = |heads: &[CommitId], roots: &[CommitId]| {
881 RevWalkBuilder::new(index)
882 .wanted_heads(to_positions_vec(index, heads))
883 .ancestors_until_roots(to_positions_vec(index, roots))
884 };
885 let to_commit_id = |pos| index.commits().entry_by_pos(pos).commit_id();
886
887 let mut iter = make_iter(&[id_6.clone(), id_7.clone()], &[id_3.clone()]);
888 assert_eq!(iter.walk.wanted_queue.len(), 2);
889 assert_eq!(iter.next().map(to_commit_id), Some(id_7.clone()));
890 assert_eq!(iter.next().map(to_commit_id), Some(id_6.clone()));
891 assert_eq!(iter.next().map(to_commit_id), Some(id_5.clone()));
892 assert_eq!(iter.walk.wanted_queue.len(), 2);
893 assert_eq!(iter.next().map(to_commit_id), Some(id_4.clone()));
894 assert_eq!(iter.walk.wanted_queue.len(), 1); // id_1 shouldn't be queued
895 assert_eq!(iter.next().map(to_commit_id), Some(id_3.clone()));
896 assert_eq!(iter.walk.wanted_queue.len(), 0); // id_2 shouldn't be queued
897 assert!(iter.next().is_none());
898
899 let iter = make_iter(&[id_6.clone(), id_7.clone(), id_2.clone()], &[id_3.clone()]);
900 assert_eq!(iter.walk.wanted_queue.len(), 2); // id_2 shouldn't be queued
901
902 let iter = make_iter(&[id_6.clone(), id_7.clone()], &[]);
903 assert_eq!(iter.walk.wanted_queue.len(), 0); // no ids should be queued
904 }
905
906 #[test]
907 fn test_walk_ancestors_filtered_by_generation() {
908 let mut new_change_id = change_id_generator();
909 let mut index = DefaultMutableIndex::full(TEST_FIELD_LENGTHS);
910 // 8 6
911 // | |
912 // 7 5
913 // |/|
914 // 4 |
915 // | 3
916 // 2 |
917 // |/
918 // 1
919 // |
920 // 0
921 let id_0 = CommitId::from_hex("000000");
922 let id_1 = CommitId::from_hex("111111");
923 let id_2 = CommitId::from_hex("222222");
924 let id_3 = CommitId::from_hex("333333");
925 let id_4 = CommitId::from_hex("444444");
926 let id_5 = CommitId::from_hex("555555");
927 let id_6 = CommitId::from_hex("666666");
928 let id_7 = CommitId::from_hex("777777");
929 let id_8 = CommitId::from_hex("888888");
930 index.add_commit_data(id_0.clone(), new_change_id(), &[]);
931 index.add_commit_data(id_1.clone(), new_change_id(), &[id_0.clone()]);
932 index.add_commit_data(id_2.clone(), new_change_id(), &[id_1.clone()]);
933 index.add_commit_data(id_3.clone(), new_change_id(), &[id_1.clone()]);
934 index.add_commit_data(id_4.clone(), new_change_id(), &[id_2.clone()]);
935 index.add_commit_data(id_5.clone(), new_change_id(), &[id_4.clone(), id_3.clone()]);
936 index.add_commit_data(id_6.clone(), new_change_id(), &[id_5.clone()]);
937 index.add_commit_data(id_7.clone(), new_change_id(), &[id_4.clone()]);
938 index.add_commit_data(id_8.clone(), new_change_id(), &[id_7.clone()]);
939
940 let walk_commit_ids = |wanted: &[CommitId], unwanted: &[CommitId], range: Range<u32>| {
941 let index = index.as_composite();
942 RevWalkBuilder::new(index)
943 .wanted_heads(to_positions_vec(index, wanted))
944 .unwanted_roots(to_positions_vec(index, unwanted))
945 .ancestors_filtered_by_generation(range)
946 .map(|pos| index.commits().entry_by_pos(pos).commit_id())
947 .collect_vec()
948 };
949
950 // Empty generation bounds
951 assert_eq!(walk_commit_ids(&[&id_8].map(Clone::clone), &[], 0..0), []);
952 assert_eq!(
953 walk_commit_ids(&[&id_8].map(Clone::clone), &[], Range { start: 2, end: 1 }),
954 []
955 );
956
957 // Simple generation bounds
958 assert_eq!(
959 walk_commit_ids(&[&id_2].map(Clone::clone), &[], 0..3),
960 [&id_2, &id_1, &id_0].map(Clone::clone)
961 );
962
963 // Ancestors may be walked with different generations
964 assert_eq!(
965 walk_commit_ids(&[&id_6].map(Clone::clone), &[], 2..4),
966 [&id_4, &id_3, &id_2, &id_1].map(Clone::clone)
967 );
968 assert_eq!(
969 walk_commit_ids(&[&id_5].map(Clone::clone), &[], 2..3),
970 [&id_2, &id_1].map(Clone::clone)
971 );
972 assert_eq!(
973 walk_commit_ids(&[&id_5, &id_7].map(Clone::clone), &[], 2..3),
974 [&id_2, &id_1].map(Clone::clone)
975 );
976 assert_eq!(
977 walk_commit_ids(&[&id_7, &id_8].map(Clone::clone), &[], 0..2),
978 [&id_8, &id_7, &id_4].map(Clone::clone)
979 );
980 assert_eq!(
981 walk_commit_ids(&[&id_6, &id_7].map(Clone::clone), &[], 0..3),
982 [&id_7, &id_6, &id_5, &id_4, &id_3, &id_2].map(Clone::clone)
983 );
984 assert_eq!(
985 walk_commit_ids(&[&id_6, &id_7].map(Clone::clone), &[], 2..3),
986 [&id_4, &id_3, &id_2].map(Clone::clone)
987 );
988
989 // Ancestors of both wanted and unwanted commits are not walked
990 assert_eq!(
991 walk_commit_ids(&[&id_5].map(Clone::clone), &[&id_2].map(Clone::clone), 1..5),
992 [&id_4, &id_3].map(Clone::clone)
993 );
994 }
995
996 #[test]
997 #[expect(clippy::redundant_clone)] // allow id_n.clone()
998 fn test_walk_ancestors_filtered_by_generation_range_merging() {
999 let mut new_change_id = change_id_generator();
1000 let mut index = DefaultMutableIndex::full(TEST_FIELD_LENGTHS);
1001 // Long linear history with some short branches
1002 let ids = (0..11)
1003 .map(|n| CommitId::try_from_hex(format!("{n:06x}")).unwrap())
1004 .collect_vec();
1005 index.add_commit_data(ids[0].clone(), new_change_id(), &[]);
1006 for i in 1..ids.len() {
1007 index.add_commit_data(ids[i].clone(), new_change_id(), &[ids[i - 1].clone()]);
1008 }
1009 let id_branch5_0 = CommitId::from_hex("050000");
1010 let id_branch5_1 = CommitId::from_hex("050001");
1011 index.add_commit_data(id_branch5_0.clone(), new_change_id(), &[ids[5].clone()]);
1012 index.add_commit_data(
1013 id_branch5_1.clone(),
1014 new_change_id(),
1015 &[id_branch5_0.clone()],
1016 );
1017
1018 let walk_commit_ids = |wanted: &[CommitId], range: Range<u32>| {
1019 let index = index.as_composite();
1020 RevWalkBuilder::new(index)
1021 .wanted_heads(to_positions_vec(index, wanted))
1022 .ancestors_filtered_by_generation(range)
1023 .map(|pos| index.commits().entry_by_pos(pos).commit_id())
1024 .collect_vec()
1025 };
1026
1027 // Multiple non-overlapping generation ranges to track:
1028 // 9->6: 3..5, 6: 0..2
1029 assert_eq!(
1030 walk_commit_ids(&[&ids[9], &ids[6]].map(Clone::clone), 4..6),
1031 [&ids[5], &ids[4], &ids[2], &ids[1]].map(Clone::clone)
1032 );
1033
1034 // Multiple non-overlapping generation ranges to track, and merged later:
1035 // 10->7: 3..5, 7: 0..2
1036 // 10->6: 4..6, 7->6, 1..3, 6: 0..2
1037 assert_eq!(
1038 walk_commit_ids(&[&ids[10], &ids[7], &ids[6]].map(Clone::clone), 5..7),
1039 [&ids[5], &ids[4], &ids[2], &ids[1], &ids[0]].map(Clone::clone)
1040 );
1041
1042 // Merge range with sub-range (1..4 + 2..3 should be 1..4, not 1..3):
1043 // 8,7,6->5::1..4, B5_1->5::2..3
1044 assert_eq!(
1045 walk_commit_ids(
1046 &[&ids[8], &ids[7], &ids[6], &id_branch5_1].map(Clone::clone),
1047 5..6
1048 ),
1049 [&ids[3], &ids[2], &ids[1]].map(Clone::clone)
1050 );
1051 }
1052
1053 #[test]
1054 fn test_walk_descendants_filtered_by_generation() {
1055 let mut new_change_id = change_id_generator();
1056 let mut index = DefaultMutableIndex::full(TEST_FIELD_LENGTHS);
1057 // 8 6
1058 // | |
1059 // 7 5
1060 // |/|
1061 // 4 |
1062 // | 3
1063 // 2 |
1064 // |/
1065 // 1
1066 // |
1067 // 0
1068 let id_0 = CommitId::from_hex("000000");
1069 let id_1 = CommitId::from_hex("111111");
1070 let id_2 = CommitId::from_hex("222222");
1071 let id_3 = CommitId::from_hex("333333");
1072 let id_4 = CommitId::from_hex("444444");
1073 let id_5 = CommitId::from_hex("555555");
1074 let id_6 = CommitId::from_hex("666666");
1075 let id_7 = CommitId::from_hex("777777");
1076 let id_8 = CommitId::from_hex("888888");
1077 index.add_commit_data(id_0.clone(), new_change_id(), &[]);
1078 index.add_commit_data(id_1.clone(), new_change_id(), &[id_0.clone()]);
1079 index.add_commit_data(id_2.clone(), new_change_id(), &[id_1.clone()]);
1080 index.add_commit_data(id_3.clone(), new_change_id(), &[id_1.clone()]);
1081 index.add_commit_data(id_4.clone(), new_change_id(), &[id_2.clone()]);
1082 index.add_commit_data(id_5.clone(), new_change_id(), &[id_4.clone(), id_3.clone()]);
1083 index.add_commit_data(id_6.clone(), new_change_id(), &[id_5.clone()]);
1084 index.add_commit_data(id_7.clone(), new_change_id(), &[id_4.clone()]);
1085 index.add_commit_data(id_8.clone(), new_change_id(), &[id_7.clone()]);
1086
1087 let visible_heads = [&id_6, &id_8].map(Clone::clone);
1088 let walk_commit_ids = |roots: &[CommitId], heads: &[CommitId], range: Range<u32>| {
1089 let index = index.as_composite();
1090 RevWalkBuilder::new(index)
1091 .wanted_heads(to_positions_vec(index, heads))
1092 .descendants_filtered_by_generation(to_positions_vec(index, roots), range)
1093 .map(|Reverse(pos)| index.commits().entry_by_pos(pos).commit_id())
1094 .collect_vec()
1095 };
1096
1097 // Empty generation bounds
1098 assert_eq!(
1099 walk_commit_ids(&[&id_0].map(Clone::clone), &visible_heads, 0..0),
1100 []
1101 );
1102 assert_eq!(
1103 walk_commit_ids(
1104 &[&id_8].map(Clone::clone),
1105 &visible_heads,
1106 Range { start: 2, end: 1 }
1107 ),
1108 []
1109 );
1110
1111 // Full generation bounds
1112 assert_eq!(
1113 walk_commit_ids(&[&id_0].map(Clone::clone), &visible_heads, 0..u32::MAX),
1114 [
1115 &id_0, &id_1, &id_2, &id_3, &id_4, &id_5, &id_6, &id_7, &id_8
1116 ]
1117 .map(Clone::clone)
1118 );
1119
1120 // Simple generation bounds
1121 assert_eq!(
1122 walk_commit_ids(&[&id_3].map(Clone::clone), &visible_heads, 0..3),
1123 [&id_3, &id_5, &id_6].map(Clone::clone)
1124 );
1125
1126 // Descendants may be walked with different generations
1127 assert_eq!(
1128 walk_commit_ids(&[&id_0].map(Clone::clone), &visible_heads, 2..4),
1129 [&id_2, &id_3, &id_4, &id_5].map(Clone::clone)
1130 );
1131 assert_eq!(
1132 walk_commit_ids(&[&id_1].map(Clone::clone), &visible_heads, 2..3),
1133 [&id_4, &id_5].map(Clone::clone)
1134 );
1135 assert_eq!(
1136 walk_commit_ids(&[&id_2, &id_3].map(Clone::clone), &visible_heads, 2..3),
1137 [&id_5, &id_6, &id_7].map(Clone::clone)
1138 );
1139 assert_eq!(
1140 walk_commit_ids(&[&id_2, &id_4].map(Clone::clone), &visible_heads, 0..2),
1141 [&id_2, &id_4, &id_5, &id_7].map(Clone::clone)
1142 );
1143 assert_eq!(
1144 walk_commit_ids(&[&id_2, &id_3].map(Clone::clone), &visible_heads, 0..3),
1145 [&id_2, &id_3, &id_4, &id_5, &id_6, &id_7].map(Clone::clone)
1146 );
1147 assert_eq!(
1148 walk_commit_ids(&[&id_2, &id_3].map(Clone::clone), &visible_heads, 2..3),
1149 [&id_5, &id_6, &id_7].map(Clone::clone)
1150 );
1151
1152 // Roots set contains entries unreachable from heads
1153 assert_eq!(
1154 walk_commit_ids(
1155 &[&id_2, &id_3].map(Clone::clone),
1156 &[&id_8].map(Clone::clone),
1157 0..3
1158 ),
1159 [&id_2, &id_4, &id_7].map(Clone::clone)
1160 );
1161 }
1162 }