Debian Codegraph @

rust/hg-core/src/dagops.rs

raw
1 // dagops.rs
2 //
3 // Copyright 2019 Georges Racinet <[email protected]>
4 //
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
7
8 //! Miscellaneous DAG operations
9 //!
10 //! # Terminology
11 //! - By *relative heads* of a collection of revision numbers (`Revision`), we
12 //! mean those revisions that have no children among the collection.
13 //! - Similarly *relative roots* of a collection of `Revision`, we mean those
14 //! whose parents, if any, don't belong to the collection.
15 use std::collections::BTreeSet;
16 use std::collections::HashSet;
17
18 use bitvec::slice::BitSlice;
19
20 use super::Graph;
21 use super::GraphError;
22 use super::Revision;
23 use super::NULL_REVISION;
24 use crate::ancestors::AncestorsIterator;
25 use crate::BaseRevision;
26
27 fn remove_parents<S: std::hash::BuildHasher>(
28 graph: &impl Graph,
29 rev: Revision,
30 set: &mut HashSet<Revision, S>,
31 ) -> Result<(), GraphError> {
32 for parent in graph.parents(rev)?.iter() {
33 if *parent != NULL_REVISION {
34 set.remove(parent);
35 }
36 }
37 Ok(())
38 }
39
40 /// Relative heads out of some revisions, passed as an iterator.
41 ///
42 /// These heads are defined as those revisions that have no children
43 /// among those emitted by the iterator.
44 ///
45 /// # Performance notes
46 /// Internally, this clones the iterator, and builds a `HashSet` out of it.
47 ///
48 /// This function takes an `Iterator` instead of `impl IntoIterator` to
49 /// guarantee that cloning the iterator doesn't result in cloning the full
50 /// construct it comes from.
51 pub fn heads<'a>(
52 graph: &impl Graph,
53 iter_revs: impl Clone + Iterator<Item = &'a Revision>,
54 ) -> Result<HashSet<Revision>, GraphError> {
55 let mut heads: HashSet<Revision> = iter_revs.clone().cloned().collect();
56 heads.remove(&NULL_REVISION);
57 for rev in iter_revs {
58 if *rev != NULL_REVISION {
59 remove_parents(graph, *rev, &mut heads)?;
60 }
61 }
62 Ok(heads)
63 }
64
65 /// Retain in `revs` only its relative heads.
66 ///
67 /// This is an in-place operation, so that control of the incoming
68 /// set is left to the caller.
69 /// - a direct Python binding would probably need to build its own `HashSet`
70 /// from an incoming iterable, even if its sole purpose is to extract the
71 /// heads.
72 /// - a Rust caller can decide whether cloning beforehand is appropriate
73 ///
74 /// # Performance notes
75 /// Internally, this function will store a full copy of `revs` in a `Vec`.
76 pub fn retain_heads<S: std::hash::BuildHasher>(
77 graph: &impl Graph,
78 revs: &mut HashSet<Revision, S>,
79 ) -> Result<(), GraphError> {
80 revs.remove(&NULL_REVISION);
81 // we need to construct an iterable copy of revs to avoid itering while
82 // mutating
83 let as_vec: Vec<Revision> = revs.iter().cloned().collect();
84 for rev in as_vec {
85 if rev != NULL_REVISION {
86 remove_parents(graph, rev, revs)?;
87 }
88 }
89 Ok(())
90 }
91
92 /// Optimized version of `retain_heads` that expects an zeroed bitvec of the
93 /// size of the graph, to act as a faster but less space-efficient `HashSet`.
94 ///
95 /// # Panics
96 ///
97 /// Can panic if `not_heads` is shorten than the length of graph.
98 pub fn retain_heads_fast(
99 graph: &impl Graph,
100 not_heads: &mut BitSlice,
101 filtered_revs: &HashSet<Revision>,
102 ) -> Result<(), GraphError> {
103 for idx in (0..not_heads.len()).rev() {
104 let rev = Revision(idx as BaseRevision);
105 if !not_heads[idx] && filtered_revs.contains(&rev) {
106 not_heads.get_mut(idx).unwrap().commit(true);
107 continue;
108 }
109 for parent in graph.parents(rev)?.iter() {
110 if *parent != NULL_REVISION {
111 not_heads.get_mut(parent.0 as usize).unwrap().commit(true);
112 }
113 }
114 }
115 Ok(())
116 }
117
118 /// Roots of `revs`, passed as a `HashSet`
119 ///
120 /// They are returned in arbitrary order
121 pub fn roots<G: Graph, S: std::hash::BuildHasher>(
122 graph: &G,
123 revs: &HashSet<Revision, S>,
124 ) -> Result<Vec<Revision>, GraphError> {
125 let mut roots: Vec<Revision> = Vec::new();
126 for rev in revs {
127 if graph
128 .parents(*rev)?
129 .iter()
130 .filter(|p| **p != NULL_REVISION)
131 .all(|p| !revs.contains(p))
132 {
133 roots.push(*rev);
134 }
135 }
136 Ok(roots)
137 }
138
139 /// Compute the topological range between two collections of revisions
140 ///
141 /// This is equivalent to the revset `<roots>::<heads>`.
142 ///
143 /// Currently, the given `Graph` has to implement `Clone`, which means
144 /// actually cloning just a reference-counted Python pointer if
145 /// it's passed over through `rust-pyo3`. This is due to the internal
146 /// use of `AncestorsIterator`
147 ///
148 /// # Algorithmic details
149 ///
150 /// This is a two-pass swipe inspired from what `reachableroots2` from
151 /// `mercurial.cext.parsers` does to obtain the same results.
152 ///
153 /// - first, we climb up the DAG from `heads` in topological order, keeping them
154 /// in the vector `heads_ancestors` vector, and adding any element of `roots`
155 /// we find among them to the resulting range.
156 /// - Then, we iterate on that recorded vector so that a revision is always
157 /// emitted after its parents and add all revisions whose parents are already
158 /// in the range to the results.
159 ///
160 /// # Performance notes
161 ///
162 /// The main difference with the C implementation is that
163 /// the latter uses a flat array with bit flags, instead of complex structures
164 /// like `HashSet`, making it faster in most scenarios. In theory, it's
165 /// possible that the present implementation could be more memory efficient
166 /// for very large repositories with many branches.
167 pub fn range(
168 graph: &(impl Graph + Clone),
169 roots: impl IntoIterator<Item = Revision>,
170 heads: impl IntoIterator<Item = Revision>,
171 ) -> Result<BTreeSet<Revision>, GraphError> {
172 let mut range = BTreeSet::new();
173 let roots: HashSet<Revision> = roots.into_iter().collect();
174 let min_root: Revision = match roots.iter().cloned().min() {
175 None => {
176 return Ok(range);
177 }
178 Some(r) => r,
179 };
180
181 // Internally, AncestorsIterator currently maintains a `HashSet`
182 // of all seen revision, which is also what we record, albeit in an ordered
183 // way. There's room for improvement on this duplication.
184 let ait = AncestorsIterator::new(graph.clone(), heads, min_root, true)?;
185 let mut heads_ancestors: Vec<Revision> = Vec::new();
186 for revres in ait {
187 let rev = revres?;
188 if roots.contains(&rev) {
189 range.insert(rev);
190 }
191 heads_ancestors.push(rev);
192 }
193
194 for rev in heads_ancestors.into_iter().rev() {
195 for parent in graph.parents(rev)?.iter() {
196 if *parent != NULL_REVISION && range.contains(parent) {
197 range.insert(rev);
198 }
199 }
200 }
201 Ok(range)
202 }
203
204 #[cfg(test)]
205 mod tests {
206
207 use super::*;
208 use crate::testing::SampleGraph;
209 use crate::BaseRevision;
210
211 /// Apply `retain_heads()` to the given slice and return as a sorted `Vec`
212 fn retain_heads_sorted(
213 graph: &impl Graph,
214 revs: &[BaseRevision],
215 ) -> Result<Vec<Revision>, GraphError> {
216 let mut revs: HashSet<Revision> =
217 revs.iter().cloned().map(Revision).collect();
218 retain_heads(graph, &mut revs)?;
219 let mut as_vec: Vec<Revision> = revs.iter().cloned().collect();
220 as_vec.sort_unstable();
221 Ok(as_vec)
222 }
223
224 #[test]
225 fn test_retain_heads() -> Result<(), GraphError> {
226 assert_eq!(retain_heads_sorted(&SampleGraph, &[4, 5, 6])?, vec![5, 6]);
227 assert_eq!(
228 retain_heads_sorted(&SampleGraph, &[4, 1, 6, 12, 0])?,
229 vec![1, 6, 12]
230 );
231 assert_eq!(
232 retain_heads_sorted(&SampleGraph, &[1, 2, 3, 4, 5, 6, 7, 8, 9])?,
233 vec![3, 5, 8, 9]
234 );
235 Ok(())
236 }
237
238 /// Apply `heads()` to the given slice and return as a sorted `Vec`
239 fn heads_sorted(
240 graph: &impl Graph,
241 revs: &[BaseRevision],
242 ) -> Result<Vec<Revision>, GraphError> {
243 let iter_revs: Vec<_> = revs.iter().cloned().map(Revision).collect();
244 let heads = heads(graph, iter_revs.iter())?;
245 let mut as_vec: Vec<Revision> = heads.iter().cloned().collect();
246 as_vec.sort_unstable();
247 Ok(as_vec)
248 }
249
250 #[test]
251 fn test_heads() -> Result<(), GraphError> {
252 assert_eq!(heads_sorted(&SampleGraph, &[4, 5, 6])?, vec![5, 6]);
253 assert_eq!(
254 heads_sorted(&SampleGraph, &[4, 1, 6, 12, 0])?,
255 vec![1, 6, 12]
256 );
257 assert_eq!(
258 heads_sorted(&SampleGraph, &[1, 2, 3, 4, 5, 6, 7, 8, 9])?,
259 vec![3, 5, 8, 9]
260 );
261 Ok(())
262 }
263
264 /// Apply `roots()` and sort the result for easier comparison
265 fn roots_sorted(
266 graph: &impl Graph,
267 revs: &[BaseRevision],
268 ) -> Result<Vec<Revision>, GraphError> {
269 let set: HashSet<_> = revs.iter().cloned().map(Revision).collect();
270 let mut as_vec = roots(graph, &set)?;
271 as_vec.sort_unstable();
272 Ok(as_vec)
273 }
274
275 #[test]
276 fn test_roots() -> Result<(), GraphError> {
277 assert_eq!(roots_sorted(&SampleGraph, &[4, 5, 6])?, vec![4]);
278 assert_eq!(
279 roots_sorted(&SampleGraph, &[4, 1, 6, 12, 0])?,
280 vec![0, 4, 12]
281 );
282 assert_eq!(
283 roots_sorted(&SampleGraph, &[1, 2, 3, 4, 5, 6, 7, 8, 9])?,
284 vec![1, 8]
285 );
286 Ok(())
287 }
288
289 /// Apply `range()` and convert the result into a Vec for easier comparison
290 fn range_vec(
291 graph: impl Graph + Clone,
292 roots: &[BaseRevision],
293 heads: &[BaseRevision],
294 ) -> Result<Vec<Revision>, GraphError> {
295 range(
296 &graph,
297 roots.iter().cloned().map(Revision),
298 heads.iter().cloned().map(Revision),
299 )
300 .map(|bs| bs.into_iter().collect())
301 }
302
303 #[test]
304 fn test_range() -> Result<(), GraphError> {
305 assert_eq!(range_vec(SampleGraph, &[0], &[4])?, vec![0, 1, 2, 4]);
306 assert_eq!(range_vec(SampleGraph, &[0], &[8])?, Vec::<Revision>::new());
307 assert_eq!(
308 range_vec(SampleGraph, &[5, 6], &[10, 11, 13])?,
309 vec![5, 10]
310 );
311 assert_eq!(
312 range_vec(SampleGraph, &[5, 6], &[10, 12])?,
313 vec![5, 6, 9, 10, 12]
314 );
315 Ok(())
316 }
317 }