Debian Codegraph @

lib/src/default_index/composite.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::Ordering;
16 use std::cmp::Reverse;
17 use std::collections::BinaryHeap;
18 use std::collections::binary_heap;
19 use std::iter;
20 use std::mem;
21 use std::ops::Range;
22 use std::sync::Arc;
23 use std::sync::Mutex;
24
25 use async_trait::async_trait;
26 use itertools::Itertools as _;
27 use ref_cast::RefCastCustom;
28 use ref_cast::ref_cast_custom;
29
30 use super::bit_set::AncestorsBitSet;
31 use super::bit_set::PositionsBitSet;
32 use super::changed_path::CompositeChangedPathIndex;
33 use super::entry::CommitIndexEntry;
34 use super::entry::GlobalCommitPosition;
35 use super::entry::LocalCommitPosition;
36 use super::entry::SmallGlobalCommitPositionsVec;
37 use super::entry::SmallLocalCommitPositionsVec;
38 use super::mutable::MutableCommitIndexSegment;
39 use super::readonly::ReadonlyCommitIndexSegment;
40 use super::rev_walk::filter_slice_by_range;
41 use super::revset_engine;
42 use crate::backend::ChangeId;
43 use crate::backend::CommitId;
44 use crate::hex_util;
45 use crate::index::ChangeIdIndex;
46 use crate::index::Index;
47 use crate::index::IndexResult;
48 use crate::index::ResolvedChangeState;
49 use crate::index::ResolvedChangeTargets;
50 use crate::object_id::HexPrefix;
51 use crate::object_id::ObjectId as _;
52 use crate::object_id::PrefixResolution;
53 use crate::object_id::id_type;
54 use crate::repo_path::RepoPathBuf;
55 use crate::revset::ResolvedExpression;
56 use crate::revset::Revset;
57 use crate::revset::RevsetEvaluationError;
58 use crate::store::Store;
59
60 id_type!(pub(super) CommitIndexSegmentId { hex() });
61
62 pub(super) trait CommitIndexSegment: Send + Sync {
63 fn num_parent_commits(&self) -> u32;
64
65 fn num_local_commits(&self) -> u32;
66
67 fn parent_file(&self) -> Option<&Arc<ReadonlyCommitIndexSegment>>;
68
69 fn commit_id_to_pos(&self, commit_id: &CommitId) -> Option<LocalCommitPosition>;
70
71 /// Suppose the given `commit_id` exists, returns the previous and next
72 /// commit ids in lexicographical order.
73 fn resolve_neighbor_commit_ids(
74 &self,
75 commit_id: &CommitId,
76 ) -> (Option<CommitId>, Option<CommitId>);
77
78 fn resolve_commit_id_prefix(&self, prefix: &HexPrefix) -> PrefixResolution<CommitId>;
79
80 fn resolve_neighbor_change_ids(
81 &self,
82 change_id: &ChangeId,
83 ) -> (Option<ChangeId>, Option<ChangeId>);
84
85 // Returns positions in ascending order.
86 fn resolve_change_id_prefix(
87 &self,
88 prefix: &HexPrefix,
89 ) -> PrefixResolution<(ChangeId, SmallLocalCommitPositionsVec)>;
90
91 fn generation_number(&self, local_pos: LocalCommitPosition) -> u32;
92
93 fn commit_id(&self, local_pos: LocalCommitPosition) -> CommitId;
94
95 fn change_id(&self, local_pos: LocalCommitPosition) -> ChangeId;
96
97 fn num_parents(&self, local_pos: LocalCommitPosition) -> u32;
98
99 fn parent_positions(&self, local_pos: LocalCommitPosition) -> SmallGlobalCommitPositionsVec;
100 }
101
102 pub(super) type DynCommitIndexSegment = dyn CommitIndexSegment;
103
104 /// Abstraction over owned and borrowed types that can be cheaply converted to
105 /// a `CompositeIndex` reference.
106 pub(super) trait AsCompositeIndex {
107 /// Returns reference wrapper that provides global access to this index.
108 fn as_composite(&self) -> &CompositeIndex;
109 }
110
111 impl<T: AsCompositeIndex + ?Sized> AsCompositeIndex for &T {
112 fn as_composite(&self) -> &CompositeIndex {
113 <T as AsCompositeIndex>::as_composite(self)
114 }
115 }
116
117 impl<T: AsCompositeIndex + ?Sized> AsCompositeIndex for &mut T {
118 fn as_composite(&self) -> &CompositeIndex {
119 <T as AsCompositeIndex>::as_composite(self)
120 }
121 }
122
123 /// Provides an index of both commit IDs and change IDs.
124 ///
125 /// We refer to this as a composite index because it's a composite of multiple
126 /// nested index segments where each parent segment is roughly twice as large
127 /// its child. segment. This provides a good balance between read and write
128 /// performance.
129 #[derive(RefCastCustom)]
130 #[repr(transparent)]
131 pub(super) struct CompositeCommitIndex(DynCommitIndexSegment);
132
133 impl CompositeCommitIndex {
134 #[ref_cast_custom]
135 pub(super) const fn new(segment: &DynCommitIndexSegment) -> &Self;
136
137 /// Iterates parent and its ancestor readonly index segments.
138 pub(super) fn ancestor_files_without_local(
139 &self,
140 ) -> impl Iterator<Item = &Arc<ReadonlyCommitIndexSegment>> {
141 let parent_file = self.0.parent_file();
142 iter::successors(parent_file, |file| file.parent_file())
143 }
144
145 /// Iterates self and its ancestor index segments.
146 pub(super) fn ancestor_index_segments(&self) -> impl Iterator<Item = &DynCommitIndexSegment> {
147 iter::once(&self.0).chain(
148 self.ancestor_files_without_local()
149 .map(|file| file.as_ref() as &DynCommitIndexSegment),
150 )
151 }
152
153 pub fn num_commits(&self) -> u32 {
154 self.0.num_parent_commits() + self.0.num_local_commits()
155 }
156
157 pub fn has_id(&self, commit_id: &CommitId) -> bool {
158 self.commit_id_to_pos(commit_id).is_some()
159 }
160
161 pub fn entry_by_pos(&self, pos: GlobalCommitPosition) -> CommitIndexEntry<'_> {
162 self.ancestor_index_segments()
163 .find_map(|segment| {
164 u32::checked_sub(pos.0, segment.num_parent_commits())
165 .map(LocalCommitPosition)
166 .map(|local_pos| CommitIndexEntry::new(segment, pos, local_pos))
167 })
168 .unwrap()
169 }
170
171 pub fn entry_by_id(&self, commit_id: &CommitId) -> Option<CommitIndexEntry<'_>> {
172 self.ancestor_index_segments().find_map(|segment| {
173 let local_pos = segment.commit_id_to_pos(commit_id)?;
174 let pos = GlobalCommitPosition(local_pos.0 + segment.num_parent_commits());
175 Some(CommitIndexEntry::new(segment, pos, local_pos))
176 })
177 }
178
179 pub fn commit_id_to_pos(&self, commit_id: &CommitId) -> Option<GlobalCommitPosition> {
180 self.ancestor_index_segments().find_map(|segment| {
181 let LocalCommitPosition(local_pos) = segment.commit_id_to_pos(commit_id)?;
182 let pos = GlobalCommitPosition(local_pos + segment.num_parent_commits());
183 Some(pos)
184 })
185 }
186
187 pub fn resolve_commit_id_prefix(&self, prefix: &HexPrefix) -> PrefixResolution<CommitId> {
188 self.ancestor_index_segments()
189 .fold(PrefixResolution::NoMatch, |acc_match, segment| {
190 if acc_match == PrefixResolution::AmbiguousMatch {
191 acc_match // avoid checking the parent file(s)
192 } else {
193 let local_match = segment.resolve_commit_id_prefix(prefix);
194 acc_match.plus(&local_match)
195 }
196 })
197 }
198
199 /// Suppose the given `commit_id` exists, returns the minimum prefix length
200 /// to disambiguate it. The length to be returned is a number of hexadecimal
201 /// digits.
202 ///
203 /// If the given `commit_id` doesn't exist, this will return the prefix
204 /// length that never matches with any commit ids.
205 pub(super) fn shortest_unique_commit_id_prefix_len(&self, commit_id: &CommitId) -> usize {
206 let (prev_id, next_id) = self.resolve_neighbor_commit_ids(commit_id);
207 itertools::chain(prev_id, next_id)
208 .map(|id| hex_util::common_hex_len(commit_id.as_bytes(), id.as_bytes()) + 1)
209 .max()
210 .unwrap_or(0)
211 }
212
213 /// Suppose the given `commit_id` exists, returns the previous and next
214 /// commit ids in lexicographical order.
215 pub(super) fn resolve_neighbor_commit_ids(
216 &self,
217 commit_id: &CommitId,
218 ) -> (Option<CommitId>, Option<CommitId>) {
219 self.ancestor_index_segments()
220 .map(|segment| segment.resolve_neighbor_commit_ids(commit_id))
221 .reduce(|(acc_prev_id, acc_next_id), (prev_id, next_id)| {
222 (
223 acc_prev_id.into_iter().chain(prev_id).max(),
224 acc_next_id.into_iter().chain(next_id).min(),
225 )
226 })
227 .unwrap()
228 }
229
230 /// Suppose the given `change_id` exists, returns the minimum prefix length
231 /// to disambiguate it within all the indexed ids including hidden ones.
232 pub(super) fn shortest_unique_change_id_prefix_len(&self, change_id: &ChangeId) -> usize {
233 let (prev_id, next_id) = self.resolve_neighbor_change_ids(change_id);
234 itertools::chain(prev_id, next_id)
235 .map(|id| hex_util::common_hex_len(change_id.as_bytes(), id.as_bytes()) + 1)
236 .max()
237 .unwrap_or(0)
238 }
239
240 /// Suppose the given `change_id` exists, returns the previous and next
241 /// change ids in lexicographical order. The returned change ids may be
242 /// hidden.
243 pub(super) fn resolve_neighbor_change_ids(
244 &self,
245 change_id: &ChangeId,
246 ) -> (Option<ChangeId>, Option<ChangeId>) {
247 self.ancestor_index_segments()
248 .map(|segment| segment.resolve_neighbor_change_ids(change_id))
249 .reduce(|(acc_prev_id, acc_next_id), (prev_id, next_id)| {
250 (
251 acc_prev_id.into_iter().chain(prev_id).max(),
252 acc_next_id.into_iter().chain(next_id).min(),
253 )
254 })
255 .unwrap()
256 }
257
258 /// Resolves the given change id `prefix` to the associated entries. The
259 /// returned entries may be hidden.
260 ///
261 /// The returned index positions are sorted in descending order.
262 pub(super) fn resolve_change_id_prefix(
263 &self,
264 prefix: &HexPrefix,
265 ) -> PrefixResolution<(ChangeId, SmallGlobalCommitPositionsVec)> {
266 use PrefixResolution::*;
267 self.ancestor_index_segments()
268 .fold(NoMatch, |acc_match, segment| {
269 if acc_match == AmbiguousMatch {
270 return acc_match; // avoid checking the parent file(s)
271 }
272 let to_global_pos = {
273 let num_parent_commits = segment.num_parent_commits();
274 move |LocalCommitPosition(pos)| GlobalCommitPosition(pos + num_parent_commits)
275 };
276 // Similar to PrefixResolution::plus(), but merges matches of the same id.
277 match (acc_match, segment.resolve_change_id_prefix(prefix)) {
278 (NoMatch, local_match) => local_match.map(|(id, positions)| {
279 (id, positions.into_iter().rev().map(to_global_pos).collect())
280 }),
281 (acc_match, NoMatch) => acc_match,
282 (AmbiguousMatch, _) => AmbiguousMatch,
283 (_, AmbiguousMatch) => AmbiguousMatch,
284 (SingleMatch((id1, _)), SingleMatch((id2, _))) if id1 != id2 => AmbiguousMatch,
285 (SingleMatch((id, mut acc_positions)), SingleMatch((_, local_positions))) => {
286 acc_positions.extend(local_positions.into_iter().rev().map(to_global_pos));
287 SingleMatch((id, acc_positions))
288 }
289 }
290 })
291 }
292
293 /// Helper function to resolve change targets for a list of positions
294 /// according to the reahchable_set
295 /// provided. Requires positions to be in descending order.
296 pub(super) fn resolve_change_targets_for_positions(
297 &self,
298 positions: &[GlobalCommitPosition],
299 reachable_set: &mut AncestorsBitSet,
300 ) -> ResolvedChangeTargets {
301 debug_assert!(positions.is_sorted_by(|a, b| a > b));
302 reachable_set.visit_until(self, *positions.last().unwrap());
303 let targets = positions
304 .iter()
305 .map(|&pos| {
306 let commit_id = self.entry_by_pos(pos).commit_id();
307 let state = if reachable_set.contains(pos) {
308 ResolvedChangeState::Visible
309 } else {
310 ResolvedChangeState::Hidden
311 };
312 (commit_id, state)
313 })
314 .collect_vec();
315 ResolvedChangeTargets { targets }
316 }
317
318 pub fn is_ancestor(&self, ancestor_id: &CommitId, descendant_id: &CommitId) -> bool {
319 let ancestor_pos = self.commit_id_to_pos(ancestor_id).unwrap();
320 let descendant_pos = self.commit_id_to_pos(descendant_id).unwrap();
321 self.is_ancestor_pos(ancestor_pos, descendant_pos)
322 }
323
324 pub(super) fn is_ancestor_pos(
325 &self,
326 ancestor_pos: GlobalCommitPosition,
327 descendant_pos: GlobalCommitPosition,
328 ) -> bool {
329 let ancestor_generation = self.entry_by_pos(ancestor_pos).generation_number();
330 let mut work = vec![descendant_pos];
331 let mut visited = PositionsBitSet::with_max_pos(descendant_pos);
332 while let Some(descendant_pos) = work.pop() {
333 match descendant_pos.cmp(&ancestor_pos) {
334 Ordering::Less => continue,
335 Ordering::Equal => return true,
336 Ordering::Greater => {}
337 }
338 if visited.get_set(descendant_pos) {
339 continue;
340 }
341 let descendant_entry = self.entry_by_pos(descendant_pos);
342 if descendant_entry.generation_number() <= ancestor_generation {
343 continue;
344 }
345 work.extend(descendant_entry.parent_positions());
346 }
347 false
348 }
349
350 pub fn common_ancestors(&self, set1: &[CommitId], set2: &[CommitId]) -> Vec<CommitId> {
351 let pos1 = set1
352 .iter()
353 .map(|id| self.commit_id_to_pos(id).unwrap())
354 .collect_vec();
355 let pos2 = set2
356 .iter()
357 .map(|id| self.commit_id_to_pos(id).unwrap())
358 .collect_vec();
359 self.common_ancestors_pos(pos1, pos2)
360 .iter()
361 .map(|pos| self.entry_by_pos(*pos).commit_id())
362 .collect()
363 }
364
365 /// Computes the greatest common ancestors.
366 ///
367 /// The returned index positions are sorted in descending order.
368 pub(super) fn common_ancestors_pos(
369 &self,
370 set1: Vec<GlobalCommitPosition>,
371 set2: Vec<GlobalCommitPosition>,
372 ) -> Vec<GlobalCommitPosition> {
373 let mut items1 = BinaryHeap::from(set1);
374 let mut items2 = BinaryHeap::from(set2);
375 let mut result = Vec::new();
376 while let (Some(&pos1), Some(&pos2)) = (items1.peek(), items2.peek()) {
377 match pos1.cmp(&pos2) {
378 Ordering::Greater => shift_to_parents(
379 &mut items1,
380 pos1,
381 &self.entry_by_pos(pos1).parent_positions(),
382 ),
383 Ordering::Less => shift_to_parents(
384 &mut items2,
385 pos2,
386 &self.entry_by_pos(pos2).parent_positions(),
387 ),
388 Ordering::Equal => {
389 result.push(pos1);
390 dedup_pop(&mut items1).unwrap();
391 dedup_pop(&mut items2).unwrap();
392 }
393 }
394 }
395 self.heads_pos(result)
396 }
397
398 pub(super) fn all_heads(&self) -> impl Iterator<Item = CommitId> {
399 self.all_heads_pos()
400 .map(move |pos| self.entry_by_pos(pos).commit_id())
401 }
402
403 pub(super) fn all_heads_pos(&self) -> impl Iterator<Item = GlobalCommitPosition> + use<> {
404 let num_commits = self.num_commits();
405 let mut not_head = PositionsBitSet::with_capacity(num_commits);
406 for pos in (0..num_commits).map(GlobalCommitPosition) {
407 let entry = self.entry_by_pos(pos);
408 for parent_pos in entry.parent_positions() {
409 not_head.set(parent_pos);
410 }
411 }
412 (0..num_commits)
413 .map(GlobalCommitPosition)
414 // TODO: can be optimized to use leading/trailing_ones()
415 .filter(move |&pos| !not_head.get(pos))
416 }
417
418 pub fn heads<'a>(
419 &self,
420 candidate_ids: impl IntoIterator<Item = &'a CommitId>,
421 ) -> Vec<CommitId> {
422 let mut candidate_positions = candidate_ids
423 .into_iter()
424 .map(|id| self.commit_id_to_pos(id).unwrap())
425 .collect_vec();
426 candidate_positions.sort_unstable_by_key(|&pos| Reverse(pos));
427 candidate_positions.dedup();
428 self.heads_pos(candidate_positions)
429 .iter()
430 .map(|pos| self.entry_by_pos(*pos).commit_id())
431 .collect()
432 }
433
434 /// Returns the subset of positions in `candidate_positions` which refer to
435 /// entries that are heads in the repository.
436 ///
437 /// The `candidate_positions` must be sorted in descending order, and have
438 /// no duplicates. The returned head positions are also sorted in descending
439 /// order.
440 pub fn heads_pos(
441 &self,
442 candidate_positions: Vec<GlobalCommitPosition>,
443 ) -> Vec<GlobalCommitPosition> {
444 debug_assert!(candidate_positions.is_sorted_by(|a, b| a > b));
445 let Some(min_generation) = candidate_positions
446 .iter()
447 .map(|&pos| self.entry_by_pos(pos).generation_number())
448 .min()
449 else {
450 return candidate_positions;
451 };
452
453 // Iterate though the candidates by reverse index position, keeping track of the
454 // ancestors of already-found heads. If a candidate is an ancestor of an
455 // already-found head, then it can be removed.
456 let mut parents = BinaryHeap::new();
457 let mut heads = Vec::new();
458 'outer: for candidate in candidate_positions {
459 while let Some(&parent) = parents.peek().filter(|&&parent| parent >= candidate) {
460 let entry = self.entry_by_pos(parent);
461 if entry.generation_number() <= min_generation {
462 dedup_pop(&mut parents).unwrap();
463 } else {
464 shift_to_parents(&mut parents, parent, &entry.parent_positions());
465 }
466 if parent == candidate {
467 // The candidate is an ancestor of an existing head, so we can skip it.
468 continue 'outer;
469 }
470 }
471 // No parents matched, so this commit is a head.
472 let entry = self.entry_by_pos(candidate);
473 parents.extend(entry.parent_positions());
474 heads.push(candidate);
475 }
476 heads
477 }
478
479 /// Find the heads of a range of positions `roots..heads`, applying a filter
480 /// to the commits in the range. The heads are sorted in descending order.
481 /// The filter will also be called in descending index position order.
482 pub fn heads_from_range_and_filter<E>(
483 &self,
484 roots: Vec<GlobalCommitPosition>,
485 heads: Vec<GlobalCommitPosition>,
486 parents_range: &Range<u32>,
487 mut filter: impl FnMut(GlobalCommitPosition) -> Result<bool, E>,
488 ) -> Result<Vec<GlobalCommitPosition>, E> {
489 if heads.is_empty() {
490 return Ok(heads);
491 }
492 let mut wanted_queue = BinaryHeap::from(heads);
493 let mut unwanted_queue = BinaryHeap::from(roots);
494 let mut found_heads = Vec::new();
495 while let Some(&pos) = wanted_queue.peek() {
496 if shift_to_parents_until(&mut unwanted_queue, self, pos) {
497 dedup_pop(&mut wanted_queue);
498 continue;
499 }
500 let entry = self.entry_by_pos(pos);
501 if filter(pos)? {
502 dedup_pop(&mut wanted_queue);
503 unwanted_queue.extend(entry.parent_positions());
504 found_heads.push(pos);
505 } else {
506 let parent_positions = entry.parent_positions();
507 shift_to_parents(
508 &mut wanted_queue,
509 pos,
510 filter_slice_by_range(&parent_positions, parents_range),
511 );
512 }
513 }
514 Ok(found_heads)
515 }
516 }
517
518 #[derive(Clone, Debug)]
519 enum CompositeCommitIndexSegment {
520 Readonly(Arc<ReadonlyCommitIndexSegment>),
521 Mutable(Box<MutableCommitIndexSegment>),
522 }
523
524 #[derive(Clone, Debug)]
525 pub(super) struct CompositeIndex {
526 commits: CompositeCommitIndexSegment,
527 changed_paths: CompositeChangedPathIndex,
528 }
529
530 impl CompositeIndex {
531 pub(super) fn from_readonly(
532 commits: Arc<ReadonlyCommitIndexSegment>,
533 changed_paths: CompositeChangedPathIndex,
534 ) -> Self {
535 Self {
536 commits: CompositeCommitIndexSegment::Readonly(commits),
537 changed_paths,
538 }
539 }
540
541 pub(super) fn from_mutable(
542 commits: Box<MutableCommitIndexSegment>,
543 changed_paths: CompositeChangedPathIndex,
544 ) -> Self {
545 Self {
546 commits: CompositeCommitIndexSegment::Mutable(commits),
547 changed_paths,
548 }
549 }
550
551 pub(super) fn into_mutable(
552 self,
553 ) -> Option<(Box<MutableCommitIndexSegment>, CompositeChangedPathIndex)> {
554 let commits = match self.commits {
555 CompositeCommitIndexSegment::Readonly(_) => return None,
556 CompositeCommitIndexSegment::Mutable(segment) => segment,
557 };
558 Some((commits, self.changed_paths))
559 }
560
561 pub(super) fn commits(&self) -> &CompositeCommitIndex {
562 match &self.commits {
563 CompositeCommitIndexSegment::Readonly(segment) => segment.as_composite(),
564 CompositeCommitIndexSegment::Mutable(segment) => segment.as_composite(),
565 }
566 }
567
568 pub(super) fn readonly_commits(&self) -> Option<&Arc<ReadonlyCommitIndexSegment>> {
569 match &self.commits {
570 CompositeCommitIndexSegment::Readonly(segment) => Some(segment),
571 CompositeCommitIndexSegment::Mutable(_) => None,
572 }
573 }
574
575 pub(super) fn mutable_commits(&mut self) -> Option<&mut MutableCommitIndexSegment> {
576 match &mut self.commits {
577 CompositeCommitIndexSegment::Readonly(_) => None,
578 CompositeCommitIndexSegment::Mutable(segment) => Some(segment),
579 }
580 }
581
582 pub(super) fn changed_paths(&self) -> &CompositeChangedPathIndex {
583 &self.changed_paths
584 }
585
586 pub(super) fn changed_paths_mut(&mut self) -> &mut CompositeChangedPathIndex {
587 &mut self.changed_paths
588 }
589 }
590
591 impl AsCompositeIndex for CompositeIndex {
592 fn as_composite(&self) -> &CompositeIndex {
593 self
594 }
595 }
596
597 // In revset engine, we need to convert &CompositeIndex to &dyn Index.
598 #[async_trait]
599 impl Index for CompositeIndex {
600 async fn shortest_unique_commit_id_prefix_len(
601 &self,
602 commit_id: &CommitId,
603 ) -> IndexResult<usize> {
604 Ok(self
605 .commits()
606 .shortest_unique_commit_id_prefix_len(commit_id))
607 }
608
609 async fn resolve_commit_id_prefix(
610 &self,
611 prefix: &HexPrefix,
612 ) -> IndexResult<PrefixResolution<CommitId>> {
613 Ok(self.commits().resolve_commit_id_prefix(prefix))
614 }
615
616 async fn has_id(&self, commit_id: &CommitId) -> IndexResult<bool> {
617 Ok(self.commits().has_id(commit_id))
618 }
619
620 async fn is_ancestor(
621 &self,
622 ancestor_id: &CommitId,
623 descendant_id: &CommitId,
624 ) -> IndexResult<bool> {
625 Ok(self.commits().is_ancestor(ancestor_id, descendant_id))
626 }
627
628 async fn common_ancestors(
629 &self,
630 set1: &[CommitId],
631 set2: &[CommitId],
632 ) -> IndexResult<Vec<CommitId>> {
633 Ok(self.commits().common_ancestors(set1, set2))
634 }
635
636 fn all_heads_for_gc(&self) -> IndexResult<Box<dyn Iterator<Item = CommitId> + '_>> {
637 Ok(Box::new(self.commits().all_heads()))
638 }
639
640 async fn heads(
641 &self,
642 candidate_ids: &mut (dyn Iterator<Item = &CommitId> + Send),
643 ) -> IndexResult<Vec<CommitId>> {
644 Ok(self.commits().heads(candidate_ids))
645 }
646
647 async fn changed_paths_in_commit(
648 &self,
649 commit_id: &CommitId,
650 ) -> IndexResult<Option<Box<dyn Iterator<Item = RepoPathBuf> + '_>>> {
651 let Some(paths) = self
652 .commits()
653 .commit_id_to_pos(commit_id)
654 .and_then(|pos| self.changed_paths().changed_paths(pos))
655 else {
656 return Ok(None);
657 };
658 Ok(Some(Box::new(paths.map(|path| path.to_owned()))))
659 }
660
661 fn evaluate_revset(
662 &self,
663 expression: &ResolvedExpression,
664 store: &Arc<Store>,
665 ) -> Result<Box<dyn Revset + '_>, RevsetEvaluationError> {
666 let revset_impl = revset_engine::evaluate(expression, store, self)?;
667 Ok(Box::new(revset_impl))
668 }
669 }
670
671 pub(super) struct ChangeIdIndexImpl<I> {
672 index: I,
673 reachable_set: Mutex<AncestorsBitSet>,
674 }
675
676 impl<I: AsCompositeIndex> ChangeIdIndexImpl<I> {
677 pub fn new(index: I, heads: &mut dyn Iterator<Item = &CommitId>) -> Self {
678 let composite = index.as_composite().commits();
679 let mut reachable_set = AncestorsBitSet::with_capacity(composite.num_commits());
680 for id in heads {
681 reachable_set.add_head(composite.commit_id_to_pos(id).unwrap());
682 }
683 Self {
684 index,
685 reachable_set: Mutex::new(reachable_set),
686 }
687 }
688 }
689
690 #[async_trait]
691 impl<I: AsCompositeIndex + Send + Sync> ChangeIdIndex for ChangeIdIndexImpl<I> {
692 // Resolves change ID prefix among all IDs.
693 //
694 // If `SingleMatch` is returned, there is at least one commit with the given
695 // change ID (either visible or hidden). `AmbiguousMatch` may be returned even
696 // if the prefix is unique within the visible entries.
697 async fn resolve_prefix(
698 &self,
699 prefix: &HexPrefix,
700 ) -> IndexResult<PrefixResolution<ResolvedChangeTargets>> {
701 let index = self.index.as_composite().commits();
702 Ok(index
703 .resolve_change_id_prefix(prefix)
704 .map(|(_change_id, positions)| {
705 let mut reachable_set = self.reachable_set.lock().unwrap();
706 index.resolve_change_targets_for_positions(&positions, &mut reachable_set)
707 }))
708 }
709
710 // Calculates the shortest prefix length of the given `change_id` among all
711 // IDs, including hidden entries.
712 //
713 // The returned length is usually a few digits longer than the minimum
714 // length necessary to disambiguate within the visible entries since hidden
715 // entries are also considered when determining the prefix length.
716 async fn shortest_unique_prefix_len(&self, change_id: &ChangeId) -> IndexResult<usize> {
717 let index = self.index.as_composite().commits();
718 Ok(index.shortest_unique_change_id_prefix_len(change_id))
719 }
720 }
721
722 /// Repeatedly `shift_to_parents` until reaching a target position. Returns true
723 /// if the target position matched a position in the queue.
724 fn shift_to_parents_until(
725 queue: &mut BinaryHeap<GlobalCommitPosition>,
726 index: &CompositeCommitIndex,
727 target_pos: GlobalCommitPosition,
728 ) -> bool {
729 while let Some(&pos) = queue.peek().filter(|&&pos| pos >= target_pos) {
730 shift_to_parents(queue, pos, &index.entry_by_pos(pos).parent_positions());
731 if pos == target_pos {
732 return true;
733 }
734 }
735 false
736 }
737
738 /// Removes an entry from the queue and replace it with its parents.
739 fn shift_to_parents(
740 items: &mut BinaryHeap<GlobalCommitPosition>,
741 pos: GlobalCommitPosition,
742 parent_positions: &[GlobalCommitPosition],
743 ) {
744 let mut parent_positions = parent_positions.iter();
745 if let Some(&parent_pos) = parent_positions.next() {
746 assert!(parent_pos < pos);
747 dedup_replace(items, parent_pos).unwrap();
748 } else {
749 dedup_pop(items).unwrap();
750 return;
751 }
752 for &parent_pos in parent_positions {
753 assert!(parent_pos < pos);
754 items.push(parent_pos);
755 }
756 }
757
758 /// Removes the greatest items (including duplicates) from the heap, returns
759 /// one.
760 fn dedup_pop<T: Ord>(heap: &mut BinaryHeap<T>) -> Option<T> {
761 let item = heap.pop()?;
762 remove_dup(heap, &item);
763 Some(item)
764 }
765
766 /// Removes the greatest items (including duplicates) from the heap, inserts
767 /// lesser `new_item` to the heap, returns the removed one.
768 ///
769 /// This is faster than calling `dedup_pop(heap)` and `heap.push(new_item)`
770 /// especially when `new_item` is the next greatest item.
771 fn dedup_replace<T: Ord>(heap: &mut BinaryHeap<T>, new_item: T) -> Option<T> {
772 let old_item = {
773 let mut x = heap.peek_mut()?;
774 mem::replace(&mut *x, new_item)
775 };
776 remove_dup(heap, &old_item);
777 Some(old_item)
778 }
779
780 fn remove_dup<T: Ord>(heap: &mut BinaryHeap<T>, item: &T) {
781 while let Some(x) = heap.peek_mut().filter(|x| **x == *item) {
782 binary_heap::PeekMut::pop(x);
783 }
784 }