##// END OF EJS Templates
rust: factorized testing Graphs...
Georges Racinet -
r41277:168041fa default
parent child Browse files
Show More
@@ -0,0 +1,72 b''
1 // testing.rs
2 //
3 // Copyright 2018 Georges Racinet <georges.racinet@octobus.net>
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 use crate::{Graph, GraphError, Revision, NULL_REVISION};
9
10 /// A stub `Graph`, same as the one from `test-ancestor.py`
11 ///
12 /// o 13
13 /// |
14 /// | o 12
15 /// | |
16 /// | | o 11
17 /// | | |\
18 /// | | | | o 10
19 /// | | | | |
20 /// | o---+ | 9
21 /// | | | | |
22 /// o | | | | 8
23 /// / / / /
24 /// | | o | 7
25 /// | | | |
26 /// o---+ | 6
27 /// / / /
28 /// | | o 5
29 /// | |/
30 /// | o 4
31 /// | |
32 /// o | 3
33 /// | |
34 /// | o 2
35 /// |/
36 /// o 1
37 /// |
38 /// o 0
39 #[derive(Clone, Debug)]
40 pub struct SampleGraph;
41
42 impl Graph for SampleGraph {
43 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
44 match rev {
45 0 => Ok([NULL_REVISION, NULL_REVISION]),
46 1 => Ok([0, NULL_REVISION]),
47 2 => Ok([1, NULL_REVISION]),
48 3 => Ok([1, NULL_REVISION]),
49 4 => Ok([2, NULL_REVISION]),
50 5 => Ok([4, NULL_REVISION]),
51 6 => Ok([4, NULL_REVISION]),
52 7 => Ok([4, NULL_REVISION]),
53 8 => Ok([NULL_REVISION, NULL_REVISION]),
54 9 => Ok([6, 7]),
55 10 => Ok([5, NULL_REVISION]),
56 11 => Ok([3, 7]),
57 12 => Ok([9, NULL_REVISION]),
58 13 => Ok([8, NULL_REVISION]),
59 r => Err(GraphError::ParentOutOfRange(r)),
60 }
61 }
62 }
63
64 // A Graph represented by a vector whose indices are revisions
65 // and values are parents of the revisions
66 pub type VecGraph = Vec<[Revision; 2]>;
67
68 impl Graph for VecGraph {
69 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
70 Ok(self[rev as usize])
71 }
72 }
@@ -1,775 +1,754 b''
1 // ancestors.rs
1 // ancestors.rs
2 //
2 //
3 // Copyright 2018 Georges Racinet <gracinet@anybox.fr>
3 // Copyright 2018 Georges Racinet <gracinet@anybox.fr>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
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.
6 // GNU General Public License version 2 or any later version.
7
7
8 //! Rust versions of generic DAG ancestors algorithms for Mercurial
8 //! Rust versions of generic DAG ancestors algorithms for Mercurial
9
9
10 use super::{Graph, GraphError, Revision, NULL_REVISION};
10 use super::{Graph, GraphError, Revision, NULL_REVISION};
11 use std::cmp::max;
11 use std::cmp::max;
12 use std::collections::{BinaryHeap, HashSet};
12 use std::collections::{BinaryHeap, HashSet};
13
13
14 /// Iterator over the ancestors of a given list of revisions
14 /// Iterator over the ancestors of a given list of revisions
15 /// This is a generic type, defined and implemented for any Graph, so that
15 /// This is a generic type, defined and implemented for any Graph, so that
16 /// it's easy to
16 /// it's easy to
17 ///
17 ///
18 /// - unit test in pure Rust
18 /// - unit test in pure Rust
19 /// - bind to main Mercurial code, potentially in several ways and have these
19 /// - bind to main Mercurial code, potentially in several ways and have these
20 /// bindings evolve over time
20 /// bindings evolve over time
21 pub struct AncestorsIterator<G: Graph> {
21 pub struct AncestorsIterator<G: Graph> {
22 graph: G,
22 graph: G,
23 visit: BinaryHeap<Revision>,
23 visit: BinaryHeap<Revision>,
24 seen: HashSet<Revision>,
24 seen: HashSet<Revision>,
25 stoprev: Revision,
25 stoprev: Revision,
26 }
26 }
27
27
28 /// Lazy ancestors set, backed by AncestorsIterator
28 /// Lazy ancestors set, backed by AncestorsIterator
29 pub struct LazyAncestors<G: Graph + Clone> {
29 pub struct LazyAncestors<G: Graph + Clone> {
30 graph: G,
30 graph: G,
31 containsiter: AncestorsIterator<G>,
31 containsiter: AncestorsIterator<G>,
32 initrevs: Vec<Revision>,
32 initrevs: Vec<Revision>,
33 stoprev: Revision,
33 stoprev: Revision,
34 inclusive: bool,
34 inclusive: bool,
35 }
35 }
36
36
37 pub struct MissingAncestors<G: Graph> {
37 pub struct MissingAncestors<G: Graph> {
38 graph: G,
38 graph: G,
39 bases: HashSet<Revision>,
39 bases: HashSet<Revision>,
40 }
40 }
41
41
42 impl<G: Graph> AncestorsIterator<G> {
42 impl<G: Graph> AncestorsIterator<G> {
43 /// Constructor.
43 /// Constructor.
44 ///
44 ///
45 /// if `inclusive` is true, then the init revisions are emitted in
45 /// if `inclusive` is true, then the init revisions are emitted in
46 /// particular, otherwise iteration starts from their parents.
46 /// particular, otherwise iteration starts from their parents.
47 pub fn new(
47 pub fn new(
48 graph: G,
48 graph: G,
49 initrevs: impl IntoIterator<Item = Revision>,
49 initrevs: impl IntoIterator<Item = Revision>,
50 stoprev: Revision,
50 stoprev: Revision,
51 inclusive: bool,
51 inclusive: bool,
52 ) -> Result<Self, GraphError> {
52 ) -> Result<Self, GraphError> {
53 let filtered_initrevs = initrevs.into_iter().filter(|&r| r >= stoprev);
53 let filtered_initrevs = initrevs.into_iter().filter(|&r| r >= stoprev);
54 if inclusive {
54 if inclusive {
55 let visit: BinaryHeap<Revision> = filtered_initrevs.collect();
55 let visit: BinaryHeap<Revision> = filtered_initrevs.collect();
56 let seen = visit.iter().map(|&x| x).collect();
56 let seen = visit.iter().map(|&x| x).collect();
57 return Ok(AncestorsIterator {
57 return Ok(AncestorsIterator {
58 visit: visit,
58 visit: visit,
59 seen: seen,
59 seen: seen,
60 stoprev: stoprev,
60 stoprev: stoprev,
61 graph: graph,
61 graph: graph,
62 });
62 });
63 }
63 }
64 let mut this = AncestorsIterator {
64 let mut this = AncestorsIterator {
65 visit: BinaryHeap::new(),
65 visit: BinaryHeap::new(),
66 seen: HashSet::new(),
66 seen: HashSet::new(),
67 stoprev: stoprev,
67 stoprev: stoprev,
68 graph: graph,
68 graph: graph,
69 };
69 };
70 this.seen.insert(NULL_REVISION);
70 this.seen.insert(NULL_REVISION);
71 for rev in filtered_initrevs {
71 for rev in filtered_initrevs {
72 for parent in this.graph.parents(rev)?.iter().cloned() {
72 for parent in this.graph.parents(rev)?.iter().cloned() {
73 this.conditionally_push_rev(parent);
73 this.conditionally_push_rev(parent);
74 }
74 }
75 }
75 }
76 Ok(this)
76 Ok(this)
77 }
77 }
78
78
79 #[inline]
79 #[inline]
80 fn conditionally_push_rev(&mut self, rev: Revision) {
80 fn conditionally_push_rev(&mut self, rev: Revision) {
81 if self.stoprev <= rev && !self.seen.contains(&rev) {
81 if self.stoprev <= rev && !self.seen.contains(&rev) {
82 self.seen.insert(rev);
82 self.seen.insert(rev);
83 self.visit.push(rev);
83 self.visit.push(rev);
84 }
84 }
85 }
85 }
86
86
87 /// Consumes partially the iterator to tell if the given target
87 /// Consumes partially the iterator to tell if the given target
88 /// revision
88 /// revision
89 /// is in the ancestors it emits.
89 /// is in the ancestors it emits.
90 /// This is meant for iterators actually dedicated to that kind of
90 /// This is meant for iterators actually dedicated to that kind of
91 /// purpose
91 /// purpose
92 pub fn contains(&mut self, target: Revision) -> Result<bool, GraphError> {
92 pub fn contains(&mut self, target: Revision) -> Result<bool, GraphError> {
93 if self.seen.contains(&target) && target != NULL_REVISION {
93 if self.seen.contains(&target) && target != NULL_REVISION {
94 return Ok(true);
94 return Ok(true);
95 }
95 }
96 for item in self {
96 for item in self {
97 let rev = item?;
97 let rev = item?;
98 if rev == target {
98 if rev == target {
99 return Ok(true);
99 return Ok(true);
100 }
100 }
101 if rev < target {
101 if rev < target {
102 return Ok(false);
102 return Ok(false);
103 }
103 }
104 }
104 }
105 Ok(false)
105 Ok(false)
106 }
106 }
107
107
108 pub fn peek(&self) -> Option<Revision> {
108 pub fn peek(&self) -> Option<Revision> {
109 self.visit.peek().map(|&r| r)
109 self.visit.peek().map(|&r| r)
110 }
110 }
111
111
112 /// Tell if the iterator is about an empty set
112 /// Tell if the iterator is about an empty set
113 ///
113 ///
114 /// The result does not depend whether the iterator has been consumed
114 /// The result does not depend whether the iterator has been consumed
115 /// or not.
115 /// or not.
116 /// This is mostly meant for iterators backing a lazy ancestors set
116 /// This is mostly meant for iterators backing a lazy ancestors set
117 pub fn is_empty(&self) -> bool {
117 pub fn is_empty(&self) -> bool {
118 if self.visit.len() > 0 {
118 if self.visit.len() > 0 {
119 return false;
119 return false;
120 }
120 }
121 if self.seen.len() > 1 {
121 if self.seen.len() > 1 {
122 return false;
122 return false;
123 }
123 }
124 // at this point, the seen set is at most a singleton.
124 // at this point, the seen set is at most a singleton.
125 // If not `self.inclusive`, it's still possible that it has only
125 // If not `self.inclusive`, it's still possible that it has only
126 // the null revision
126 // the null revision
127 self.seen.is_empty() || self.seen.contains(&NULL_REVISION)
127 self.seen.is_empty() || self.seen.contains(&NULL_REVISION)
128 }
128 }
129 }
129 }
130
130
131 /// Main implementation for the iterator
131 /// Main implementation for the iterator
132 ///
132 ///
133 /// The algorithm is the same as in `_lazyancestorsiter()` from `ancestors.py`
133 /// The algorithm is the same as in `_lazyancestorsiter()` from `ancestors.py`
134 /// with a few non crucial differences:
134 /// with a few non crucial differences:
135 ///
135 ///
136 /// - there's no filtering of invalid parent revisions. Actually, it should be
136 /// - there's no filtering of invalid parent revisions. Actually, it should be
137 /// consistent and more efficient to filter them from the end caller.
137 /// consistent and more efficient to filter them from the end caller.
138 /// - we don't have the optimization for adjacent revisions (i.e., the case
138 /// - we don't have the optimization for adjacent revisions (i.e., the case
139 /// where `p1 == rev - 1`), because it amounts to update the first element of
139 /// where `p1 == rev - 1`), because it amounts to update the first element of
140 /// the heap without sifting, which Rust's BinaryHeap doesn't let us do.
140 /// the heap without sifting, which Rust's BinaryHeap doesn't let us do.
141 /// - we save a few pushes by comparing with `stoprev` before pushing
141 /// - we save a few pushes by comparing with `stoprev` before pushing
142 impl<G: Graph> Iterator for AncestorsIterator<G> {
142 impl<G: Graph> Iterator for AncestorsIterator<G> {
143 type Item = Result<Revision, GraphError>;
143 type Item = Result<Revision, GraphError>;
144
144
145 fn next(&mut self) -> Option<Self::Item> {
145 fn next(&mut self) -> Option<Self::Item> {
146 let current = match self.visit.peek() {
146 let current = match self.visit.peek() {
147 None => {
147 None => {
148 return None;
148 return None;
149 }
149 }
150 Some(c) => *c,
150 Some(c) => *c,
151 };
151 };
152 let [p1, p2] = match self.graph.parents(current) {
152 let [p1, p2] = match self.graph.parents(current) {
153 Ok(ps) => ps,
153 Ok(ps) => ps,
154 Err(e) => return Some(Err(e)),
154 Err(e) => return Some(Err(e)),
155 };
155 };
156 if p1 < self.stoprev || self.seen.contains(&p1) {
156 if p1 < self.stoprev || self.seen.contains(&p1) {
157 self.visit.pop();
157 self.visit.pop();
158 } else {
158 } else {
159 *(self.visit.peek_mut().unwrap()) = p1;
159 *(self.visit.peek_mut().unwrap()) = p1;
160 self.seen.insert(p1);
160 self.seen.insert(p1);
161 };
161 };
162
162
163 self.conditionally_push_rev(p2);
163 self.conditionally_push_rev(p2);
164 Some(Ok(current))
164 Some(Ok(current))
165 }
165 }
166 }
166 }
167
167
168 impl<G: Graph + Clone> LazyAncestors<G> {
168 impl<G: Graph + Clone> LazyAncestors<G> {
169 pub fn new(
169 pub fn new(
170 graph: G,
170 graph: G,
171 initrevs: impl IntoIterator<Item = Revision>,
171 initrevs: impl IntoIterator<Item = Revision>,
172 stoprev: Revision,
172 stoprev: Revision,
173 inclusive: bool,
173 inclusive: bool,
174 ) -> Result<Self, GraphError> {
174 ) -> Result<Self, GraphError> {
175 let v: Vec<Revision> = initrevs.into_iter().collect();
175 let v: Vec<Revision> = initrevs.into_iter().collect();
176 Ok(LazyAncestors {
176 Ok(LazyAncestors {
177 graph: graph.clone(),
177 graph: graph.clone(),
178 containsiter: AncestorsIterator::new(
178 containsiter: AncestorsIterator::new(
179 graph,
179 graph,
180 v.iter().cloned(),
180 v.iter().cloned(),
181 stoprev,
181 stoprev,
182 inclusive,
182 inclusive,
183 )?,
183 )?,
184 initrevs: v,
184 initrevs: v,
185 stoprev: stoprev,
185 stoprev: stoprev,
186 inclusive: inclusive,
186 inclusive: inclusive,
187 })
187 })
188 }
188 }
189
189
190 pub fn contains(&mut self, rev: Revision) -> Result<bool, GraphError> {
190 pub fn contains(&mut self, rev: Revision) -> Result<bool, GraphError> {
191 self.containsiter.contains(rev)
191 self.containsiter.contains(rev)
192 }
192 }
193
193
194 pub fn is_empty(&self) -> bool {
194 pub fn is_empty(&self) -> bool {
195 self.containsiter.is_empty()
195 self.containsiter.is_empty()
196 }
196 }
197
197
198 pub fn iter(&self) -> AncestorsIterator<G> {
198 pub fn iter(&self) -> AncestorsIterator<G> {
199 // the arguments being the same as for self.containsiter, we know
199 // the arguments being the same as for self.containsiter, we know
200 // for sure that AncestorsIterator constructor can't fail
200 // for sure that AncestorsIterator constructor can't fail
201 AncestorsIterator::new(
201 AncestorsIterator::new(
202 self.graph.clone(),
202 self.graph.clone(),
203 self.initrevs.iter().cloned(),
203 self.initrevs.iter().cloned(),
204 self.stoprev,
204 self.stoprev,
205 self.inclusive,
205 self.inclusive,
206 )
206 )
207 .unwrap()
207 .unwrap()
208 }
208 }
209 }
209 }
210
210
211 impl<G: Graph> MissingAncestors<G> {
211 impl<G: Graph> MissingAncestors<G> {
212 pub fn new(graph: G, bases: impl IntoIterator<Item = Revision>) -> Self {
212 pub fn new(graph: G, bases: impl IntoIterator<Item = Revision>) -> Self {
213 let mut bases: HashSet<Revision> = bases.into_iter().collect();
213 let mut bases: HashSet<Revision> = bases.into_iter().collect();
214 if bases.is_empty() {
214 if bases.is_empty() {
215 bases.insert(NULL_REVISION);
215 bases.insert(NULL_REVISION);
216 }
216 }
217 MissingAncestors { graph, bases }
217 MissingAncestors { graph, bases }
218 }
218 }
219
219
220 pub fn has_bases(&self) -> bool {
220 pub fn has_bases(&self) -> bool {
221 self.bases.iter().any(|&b| b != NULL_REVISION)
221 self.bases.iter().any(|&b| b != NULL_REVISION)
222 }
222 }
223
223
224 /// Return a reference to current bases.
224 /// Return a reference to current bases.
225 ///
225 ///
226 /// This is useful in unit tests, but also setdiscovery.py does
226 /// This is useful in unit tests, but also setdiscovery.py does
227 /// read the bases attribute of a ancestor.missingancestors instance.
227 /// read the bases attribute of a ancestor.missingancestors instance.
228 pub fn get_bases<'a>(&'a self) -> &'a HashSet<Revision> {
228 pub fn get_bases<'a>(&'a self) -> &'a HashSet<Revision> {
229 &self.bases
229 &self.bases
230 }
230 }
231
231
232 pub fn add_bases(
232 pub fn add_bases(
233 &mut self,
233 &mut self,
234 new_bases: impl IntoIterator<Item = Revision>,
234 new_bases: impl IntoIterator<Item = Revision>,
235 ) {
235 ) {
236 self.bases.extend(new_bases);
236 self.bases.extend(new_bases);
237 }
237 }
238
238
239 /// Remove all ancestors of self.bases from the revs set (in place)
239 /// Remove all ancestors of self.bases from the revs set (in place)
240 pub fn remove_ancestors_from(
240 pub fn remove_ancestors_from(
241 &mut self,
241 &mut self,
242 revs: &mut HashSet<Revision>,
242 revs: &mut HashSet<Revision>,
243 ) -> Result<(), GraphError> {
243 ) -> Result<(), GraphError> {
244 revs.retain(|r| !self.bases.contains(r));
244 revs.retain(|r| !self.bases.contains(r));
245 // the null revision is always an ancestor
245 // the null revision is always an ancestor
246 revs.remove(&NULL_REVISION);
246 revs.remove(&NULL_REVISION);
247 if revs.is_empty() {
247 if revs.is_empty() {
248 return Ok(());
248 return Ok(());
249 }
249 }
250 // anything in revs > start is definitely not an ancestor of bases
250 // anything in revs > start is definitely not an ancestor of bases
251 // revs <= start need to be investigated
251 // revs <= start need to be investigated
252 // TODO optim: if a missingancestors is to be used several times,
252 // TODO optim: if a missingancestors is to be used several times,
253 // we shouldn't need to iterate each time on bases
253 // we shouldn't need to iterate each time on bases
254 let start = match self.bases.iter().cloned().max() {
254 let start = match self.bases.iter().cloned().max() {
255 Some(m) => m,
255 Some(m) => m,
256 None => {
256 None => {
257 // bases is empty (shouldn't happen, but let's be safe)
257 // bases is empty (shouldn't happen, but let's be safe)
258 return Ok(());
258 return Ok(());
259 }
259 }
260 };
260 };
261 // whatever happens, we'll keep at least keepcount of them
261 // whatever happens, we'll keep at least keepcount of them
262 // knowing this gives us a earlier stop condition than
262 // knowing this gives us a earlier stop condition than
263 // going all the way to the root
263 // going all the way to the root
264 let keepcount = revs.iter().filter(|r| **r > start).count();
264 let keepcount = revs.iter().filter(|r| **r > start).count();
265
265
266 let mut curr = start;
266 let mut curr = start;
267 while curr != NULL_REVISION && revs.len() > keepcount {
267 while curr != NULL_REVISION && revs.len() > keepcount {
268 if self.bases.contains(&curr) {
268 if self.bases.contains(&curr) {
269 revs.remove(&curr);
269 revs.remove(&curr);
270 self.add_parents(curr)?;
270 self.add_parents(curr)?;
271 }
271 }
272 curr -= 1;
272 curr -= 1;
273 }
273 }
274 Ok(())
274 Ok(())
275 }
275 }
276
276
277 /// Add rev's parents to self.bases
277 /// Add rev's parents to self.bases
278 #[inline]
278 #[inline]
279 fn add_parents(&mut self, rev: Revision) -> Result<(), GraphError> {
279 fn add_parents(&mut self, rev: Revision) -> Result<(), GraphError> {
280 // No need to bother the set with inserting NULL_REVISION over and
280 // No need to bother the set with inserting NULL_REVISION over and
281 // over
281 // over
282 for p in self.graph.parents(rev)?.iter().cloned() {
282 for p in self.graph.parents(rev)?.iter().cloned() {
283 if p != NULL_REVISION {
283 if p != NULL_REVISION {
284 self.bases.insert(p);
284 self.bases.insert(p);
285 }
285 }
286 }
286 }
287 Ok(())
287 Ok(())
288 }
288 }
289
289
290 /// Return all the ancestors of revs that are not ancestors of self.bases
290 /// Return all the ancestors of revs that are not ancestors of self.bases
291 ///
291 ///
292 /// This may include elements from revs.
292 /// This may include elements from revs.
293 ///
293 ///
294 /// Equivalent to the revset (::revs - ::self.bases). Revs are returned in
294 /// Equivalent to the revset (::revs - ::self.bases). Revs are returned in
295 /// revision number order, which is a topological order.
295 /// revision number order, which is a topological order.
296 pub fn missing_ancestors(
296 pub fn missing_ancestors(
297 &mut self,
297 &mut self,
298 revs: impl IntoIterator<Item = Revision>,
298 revs: impl IntoIterator<Item = Revision>,
299 ) -> Result<Vec<Revision>, GraphError> {
299 ) -> Result<Vec<Revision>, GraphError> {
300 // just for convenience and comparison with Python version
300 // just for convenience and comparison with Python version
301 let bases_visit = &mut self.bases;
301 let bases_visit = &mut self.bases;
302 let mut revs: HashSet<Revision> = revs
302 let mut revs: HashSet<Revision> = revs
303 .into_iter()
303 .into_iter()
304 .filter(|r| !bases_visit.contains(r))
304 .filter(|r| !bases_visit.contains(r))
305 .collect();
305 .collect();
306 let revs_visit = &mut revs;
306 let revs_visit = &mut revs;
307 let mut both_visit: HashSet<Revision> =
307 let mut both_visit: HashSet<Revision> =
308 revs_visit.intersection(&bases_visit).cloned().collect();
308 revs_visit.intersection(&bases_visit).cloned().collect();
309 if revs_visit.is_empty() {
309 if revs_visit.is_empty() {
310 return Ok(Vec::new());
310 return Ok(Vec::new());
311 }
311 }
312
312
313 let max_bases =
313 let max_bases =
314 bases_visit.iter().cloned().max().unwrap_or(NULL_REVISION);
314 bases_visit.iter().cloned().max().unwrap_or(NULL_REVISION);
315 let max_revs =
315 let max_revs =
316 revs_visit.iter().cloned().max().unwrap_or(NULL_REVISION);
316 revs_visit.iter().cloned().max().unwrap_or(NULL_REVISION);
317 let start = max(max_bases, max_revs);
317 let start = max(max_bases, max_revs);
318
318
319 // TODO heuristics for with_capacity()?
319 // TODO heuristics for with_capacity()?
320 let mut missing: Vec<Revision> = Vec::new();
320 let mut missing: Vec<Revision> = Vec::new();
321 for curr in (0..=start).rev() {
321 for curr in (0..=start).rev() {
322 if revs_visit.is_empty() {
322 if revs_visit.is_empty() {
323 break;
323 break;
324 }
324 }
325 if both_visit.contains(&curr) {
325 if both_visit.contains(&curr) {
326 // curr's parents might have made it into revs_visit through
326 // curr's parents might have made it into revs_visit through
327 // another path
327 // another path
328 // TODO optim: Rust's HashSet.remove returns a boolean telling
328 // TODO optim: Rust's HashSet.remove returns a boolean telling
329 // if it happened. This will spare us one set lookup
329 // if it happened. This will spare us one set lookup
330 both_visit.remove(&curr);
330 both_visit.remove(&curr);
331 for p in self.graph.parents(curr)?.iter().cloned() {
331 for p in self.graph.parents(curr)?.iter().cloned() {
332 if p == NULL_REVISION {
332 if p == NULL_REVISION {
333 continue;
333 continue;
334 }
334 }
335 revs_visit.remove(&p);
335 revs_visit.remove(&p);
336 bases_visit.insert(p);
336 bases_visit.insert(p);
337 both_visit.insert(p);
337 both_visit.insert(p);
338 }
338 }
339 } else if revs_visit.remove(&curr) {
339 } else if revs_visit.remove(&curr) {
340 missing.push(curr);
340 missing.push(curr);
341 for p in self.graph.parents(curr)?.iter().cloned() {
341 for p in self.graph.parents(curr)?.iter().cloned() {
342 if p == NULL_REVISION {
342 if p == NULL_REVISION {
343 continue;
343 continue;
344 }
344 }
345 if bases_visit.contains(&p) || both_visit.contains(&p) {
345 if bases_visit.contains(&p) || both_visit.contains(&p) {
346 // p is an ancestor of revs_visit, and is implicitly
346 // p is an ancestor of revs_visit, and is implicitly
347 // in bases_visit, which means p is ::revs & ::bases.
347 // in bases_visit, which means p is ::revs & ::bases.
348 // TODO optim: hence if bothvisit, we look up twice
348 // TODO optim: hence if bothvisit, we look up twice
349 revs_visit.remove(&p);
349 revs_visit.remove(&p);
350 bases_visit.insert(p);
350 bases_visit.insert(p);
351 both_visit.insert(p);
351 both_visit.insert(p);
352 } else {
352 } else {
353 // visit later
353 // visit later
354 revs_visit.insert(p);
354 revs_visit.insert(p);
355 }
355 }
356 }
356 }
357 } else if bases_visit.contains(&curr) {
357 } else if bases_visit.contains(&curr) {
358 for p in self.graph.parents(curr)?.iter().cloned() {
358 for p in self.graph.parents(curr)?.iter().cloned() {
359 if p == NULL_REVISION {
359 if p == NULL_REVISION {
360 continue;
360 continue;
361 }
361 }
362 if revs_visit.contains(&p) || both_visit.contains(&p) {
362 if revs_visit.contains(&p) || both_visit.contains(&p) {
363 // p is an ancestor of bases_visit, and is implicitly
363 // p is an ancestor of bases_visit, and is implicitly
364 // in revs_visit, which means p is ::revs & ::bases.
364 // in revs_visit, which means p is ::revs & ::bases.
365 // TODO optim: hence if bothvisit, we look up twice
365 // TODO optim: hence if bothvisit, we look up twice
366 revs_visit.remove(&p);
366 revs_visit.remove(&p);
367 bases_visit.insert(p);
367 bases_visit.insert(p);
368 both_visit.insert(p);
368 both_visit.insert(p);
369 } else {
369 } else {
370 bases_visit.insert(p);
370 bases_visit.insert(p);
371 }
371 }
372 }
372 }
373 }
373 }
374 }
374 }
375 missing.reverse();
375 missing.reverse();
376 Ok(missing)
376 Ok(missing)
377 }
377 }
378 }
378 }
379
379
380 #[cfg(test)]
380 #[cfg(test)]
381 mod tests {
381 mod tests {
382
382
383 use super::*;
383 use super::*;
384 use crate::testing::{SampleGraph, VecGraph};
384 use std::iter::FromIterator;
385 use std::iter::FromIterator;
385
386
386 #[derive(Clone, Debug)]
387 struct Stub;
388
389 /// This is the same as the dict from test-ancestors.py
390 impl Graph for Stub {
391 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
392 match rev {
393 0 => Ok([-1, -1]),
394 1 => Ok([0, -1]),
395 2 => Ok([1, -1]),
396 3 => Ok([1, -1]),
397 4 => Ok([2, -1]),
398 5 => Ok([4, -1]),
399 6 => Ok([4, -1]),
400 7 => Ok([4, -1]),
401 8 => Ok([-1, -1]),
402 9 => Ok([6, 7]),
403 10 => Ok([5, -1]),
404 11 => Ok([3, 7]),
405 12 => Ok([9, -1]),
406 13 => Ok([8, -1]),
407 r => Err(GraphError::ParentOutOfRange(r)),
408 }
409 }
410 }
411
412 fn list_ancestors<G: Graph>(
387 fn list_ancestors<G: Graph>(
413 graph: G,
388 graph: G,
414 initrevs: Vec<Revision>,
389 initrevs: Vec<Revision>,
415 stoprev: Revision,
390 stoprev: Revision,
416 inclusive: bool,
391 inclusive: bool,
417 ) -> Vec<Revision> {
392 ) -> Vec<Revision> {
418 AncestorsIterator::new(graph, initrevs, stoprev, inclusive)
393 AncestorsIterator::new(graph, initrevs, stoprev, inclusive)
419 .unwrap()
394 .unwrap()
420 .map(|res| res.unwrap())
395 .map(|res| res.unwrap())
421 .collect()
396 .collect()
422 }
397 }
423
398
424 #[test]
399 #[test]
425 /// Same tests as test-ancestor.py, without membership
400 /// Same tests as test-ancestor.py, without membership
426 /// (see also test-ancestor.py.out)
401 /// (see also test-ancestor.py.out)
427 fn test_list_ancestor() {
402 fn test_list_ancestor() {
428 assert_eq!(list_ancestors(Stub, vec![], 0, false), vec![]);
403 assert_eq!(list_ancestors(SampleGraph, vec![], 0, false), vec![]);
429 assert_eq!(
404 assert_eq!(
430 list_ancestors(Stub, vec![11, 13], 0, false),
405 list_ancestors(SampleGraph, vec![11, 13], 0, false),
431 vec![8, 7, 4, 3, 2, 1, 0]
406 vec![8, 7, 4, 3, 2, 1, 0]
432 );
407 );
433 assert_eq!(list_ancestors(Stub, vec![1, 3], 0, false), vec![1, 0]);
434 assert_eq!(
408 assert_eq!(
435 list_ancestors(Stub, vec![11, 13], 0, true),
409 list_ancestors(SampleGraph, vec![1, 3], 0, false),
410 vec![1, 0]
411 );
412 assert_eq!(
413 list_ancestors(SampleGraph, vec![11, 13], 0, true),
436 vec![13, 11, 8, 7, 4, 3, 2, 1, 0]
414 vec![13, 11, 8, 7, 4, 3, 2, 1, 0]
437 );
415 );
438 assert_eq!(list_ancestors(Stub, vec![11, 13], 6, false), vec![8, 7]);
439 assert_eq!(
416 assert_eq!(
440 list_ancestors(Stub, vec![11, 13], 6, true),
417 list_ancestors(SampleGraph, vec![11, 13], 6, false),
418 vec![8, 7]
419 );
420 assert_eq!(
421 list_ancestors(SampleGraph, vec![11, 13], 6, true),
441 vec![13, 11, 8, 7]
422 vec![13, 11, 8, 7]
442 );
423 );
443 assert_eq!(list_ancestors(Stub, vec![11, 13], 11, true), vec![13, 11]);
424 assert_eq!(
444 assert_eq!(list_ancestors(Stub, vec![11, 13], 12, true), vec![13]);
425 list_ancestors(SampleGraph, vec![11, 13], 11, true),
426 vec![13, 11]
427 );
445 assert_eq!(
428 assert_eq!(
446 list_ancestors(Stub, vec![10, 1], 0, true),
429 list_ancestors(SampleGraph, vec![11, 13], 12, true),
430 vec![13]
431 );
432 assert_eq!(
433 list_ancestors(SampleGraph, vec![10, 1], 0, true),
447 vec![10, 5, 4, 2, 1, 0]
434 vec![10, 5, 4, 2, 1, 0]
448 );
435 );
449 }
436 }
450
437
451 #[test]
438 #[test]
452 /// Corner case that's not directly in test-ancestors.py, but
439 /// Corner case that's not directly in test-ancestors.py, but
453 /// that happens quite often, as demonstrated by running the whole
440 /// that happens quite often, as demonstrated by running the whole
454 /// suite.
441 /// suite.
455 /// For instance, run tests/test-obsolete-checkheads.t
442 /// For instance, run tests/test-obsolete-checkheads.t
456 fn test_nullrev_input() {
443 fn test_nullrev_input() {
457 let mut iter =
444 let mut iter =
458 AncestorsIterator::new(Stub, vec![-1], 0, false).unwrap();
445 AncestorsIterator::new(SampleGraph, vec![-1], 0, false).unwrap();
459 assert_eq!(iter.next(), None)
446 assert_eq!(iter.next(), None)
460 }
447 }
461
448
462 #[test]
449 #[test]
463 fn test_contains() {
450 fn test_contains() {
464 let mut lazy =
451 let mut lazy =
465 AncestorsIterator::new(Stub, vec![10, 1], 0, true).unwrap();
452 AncestorsIterator::new(SampleGraph, vec![10, 1], 0, true).unwrap();
466 assert!(lazy.contains(1).unwrap());
453 assert!(lazy.contains(1).unwrap());
467 assert!(!lazy.contains(3).unwrap());
454 assert!(!lazy.contains(3).unwrap());
468
455
469 let mut lazy =
456 let mut lazy =
470 AncestorsIterator::new(Stub, vec![0], 0, false).unwrap();
457 AncestorsIterator::new(SampleGraph, vec![0], 0, false).unwrap();
471 assert!(!lazy.contains(NULL_REVISION).unwrap());
458 assert!(!lazy.contains(NULL_REVISION).unwrap());
472 }
459 }
473
460
474 #[test]
461 #[test]
475 fn test_peek() {
462 fn test_peek() {
476 let mut iter =
463 let mut iter =
477 AncestorsIterator::new(Stub, vec![10], 0, true).unwrap();
464 AncestorsIterator::new(SampleGraph, vec![10], 0, true).unwrap();
478 // peek() gives us the next value
465 // peek() gives us the next value
479 assert_eq!(iter.peek(), Some(10));
466 assert_eq!(iter.peek(), Some(10));
480 // but it's not been consumed
467 // but it's not been consumed
481 assert_eq!(iter.next(), Some(Ok(10)));
468 assert_eq!(iter.next(), Some(Ok(10)));
482 // and iteration resumes normally
469 // and iteration resumes normally
483 assert_eq!(iter.next(), Some(Ok(5)));
470 assert_eq!(iter.next(), Some(Ok(5)));
484
471
485 // let's drain the iterator to test peek() at the end
472 // let's drain the iterator to test peek() at the end
486 while iter.next().is_some() {}
473 while iter.next().is_some() {}
487 assert_eq!(iter.peek(), None);
474 assert_eq!(iter.peek(), None);
488 }
475 }
489
476
490 #[test]
477 #[test]
491 fn test_empty() {
478 fn test_empty() {
492 let mut iter =
479 let mut iter =
493 AncestorsIterator::new(Stub, vec![10], 0, true).unwrap();
480 AncestorsIterator::new(SampleGraph, vec![10], 0, true).unwrap();
494 assert!(!iter.is_empty());
481 assert!(!iter.is_empty());
495 while iter.next().is_some() {}
482 while iter.next().is_some() {}
496 assert!(!iter.is_empty());
483 assert!(!iter.is_empty());
497
484
498 let iter = AncestorsIterator::new(Stub, vec![], 0, true).unwrap();
485 let iter =
486 AncestorsIterator::new(SampleGraph, vec![], 0, true).unwrap();
499 assert!(iter.is_empty());
487 assert!(iter.is_empty());
500
488
501 // case where iter.seen == {NULL_REVISION}
489 // case where iter.seen == {NULL_REVISION}
502 let iter = AncestorsIterator::new(Stub, vec![0], 0, false).unwrap();
490 let iter =
491 AncestorsIterator::new(SampleGraph, vec![0], 0, false).unwrap();
503 assert!(iter.is_empty());
492 assert!(iter.is_empty());
504 }
493 }
505
494
506 /// A corrupted Graph, supporting error handling tests
495 /// A corrupted Graph, supporting error handling tests
507 #[derive(Clone, Debug)]
496 #[derive(Clone, Debug)]
508 struct Corrupted;
497 struct Corrupted;
509
498
510 impl Graph for Corrupted {
499 impl Graph for Corrupted {
511 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
500 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
512 match rev {
501 match rev {
513 1 => Ok([0, -1]),
502 1 => Ok([0, -1]),
514 r => Err(GraphError::ParentOutOfRange(r)),
503 r => Err(GraphError::ParentOutOfRange(r)),
515 }
504 }
516 }
505 }
517 }
506 }
518
507
519 #[test]
508 #[test]
520 fn test_initrev_out_of_range() {
509 fn test_initrev_out_of_range() {
521 // inclusive=false looks up initrev's parents right away
510 // inclusive=false looks up initrev's parents right away
522 match AncestorsIterator::new(Stub, vec![25], 0, false) {
511 match AncestorsIterator::new(SampleGraph, vec![25], 0, false) {
523 Ok(_) => panic!("Should have been ParentOutOfRange"),
512 Ok(_) => panic!("Should have been ParentOutOfRange"),
524 Err(e) => assert_eq!(e, GraphError::ParentOutOfRange(25)),
513 Err(e) => assert_eq!(e, GraphError::ParentOutOfRange(25)),
525 }
514 }
526 }
515 }
527
516
528 #[test]
517 #[test]
529 fn test_next_out_of_range() {
518 fn test_next_out_of_range() {
530 // inclusive=false looks up initrev's parents right away
519 // inclusive=false looks up initrev's parents right away
531 let mut iter =
520 let mut iter =
532 AncestorsIterator::new(Corrupted, vec![1], 0, false).unwrap();
521 AncestorsIterator::new(Corrupted, vec![1], 0, false).unwrap();
533 assert_eq!(iter.next(), Some(Err(GraphError::ParentOutOfRange(0))));
522 assert_eq!(iter.next(), Some(Err(GraphError::ParentOutOfRange(0))));
534 }
523 }
535
524
536 #[test]
525 #[test]
537 fn test_lazy_iter_contains() {
526 fn test_lazy_iter_contains() {
538 let mut lazy =
527 let mut lazy =
539 LazyAncestors::new(Stub, vec![11, 13], 0, false).unwrap();
528 LazyAncestors::new(SampleGraph, vec![11, 13], 0, false).unwrap();
540
529
541 let revs: Vec<Revision> = lazy.iter().map(|r| r.unwrap()).collect();
530 let revs: Vec<Revision> = lazy.iter().map(|r| r.unwrap()).collect();
542 // compare with iterator tests on the same initial revisions
531 // compare with iterator tests on the same initial revisions
543 assert_eq!(revs, vec![8, 7, 4, 3, 2, 1, 0]);
532 assert_eq!(revs, vec![8, 7, 4, 3, 2, 1, 0]);
544
533
545 // contains() results are correct, unaffected by the fact that
534 // contains() results are correct, unaffected by the fact that
546 // we consumed entirely an iterator out of lazy
535 // we consumed entirely an iterator out of lazy
547 assert_eq!(lazy.contains(2), Ok(true));
536 assert_eq!(lazy.contains(2), Ok(true));
548 assert_eq!(lazy.contains(9), Ok(false));
537 assert_eq!(lazy.contains(9), Ok(false));
549 }
538 }
550
539
551 #[test]
540 #[test]
552 fn test_lazy_contains_iter() {
541 fn test_lazy_contains_iter() {
553 let mut lazy =
542 let mut lazy =
554 LazyAncestors::new(Stub, vec![11, 13], 0, false).unwrap(); // reminder: [8, 7, 4, 3, 2, 1, 0]
543 LazyAncestors::new(SampleGraph, vec![11, 13], 0, false).unwrap(); // reminder: [8, 7, 4, 3, 2, 1, 0]
555
544
556 assert_eq!(lazy.contains(2), Ok(true));
545 assert_eq!(lazy.contains(2), Ok(true));
557 assert_eq!(lazy.contains(6), Ok(false));
546 assert_eq!(lazy.contains(6), Ok(false));
558
547
559 // after consumption of 2 by the inner iterator, results stay
548 // after consumption of 2 by the inner iterator, results stay
560 // consistent
549 // consistent
561 assert_eq!(lazy.contains(2), Ok(true));
550 assert_eq!(lazy.contains(2), Ok(true));
562 assert_eq!(lazy.contains(5), Ok(false));
551 assert_eq!(lazy.contains(5), Ok(false));
563
552
564 // iter() still gives us a fresh iterator
553 // iter() still gives us a fresh iterator
565 let revs: Vec<Revision> = lazy.iter().map(|r| r.unwrap()).collect();
554 let revs: Vec<Revision> = lazy.iter().map(|r| r.unwrap()).collect();
566 assert_eq!(revs, vec![8, 7, 4, 3, 2, 1, 0]);
555 assert_eq!(revs, vec![8, 7, 4, 3, 2, 1, 0]);
567 }
556 }
568
557
569 #[test]
558 #[test]
570 /// Test constructor, add/get bases
559 /// Test constructor, add/get bases
571 fn test_missing_bases() {
560 fn test_missing_bases() {
572 let mut missing_ancestors =
561 let mut missing_ancestors =
573 MissingAncestors::new(Stub, [5, 3, 1, 3].iter().cloned());
562 MissingAncestors::new(SampleGraph, [5, 3, 1, 3].iter().cloned());
574 let mut as_vec: Vec<Revision> =
563 let mut as_vec: Vec<Revision> =
575 missing_ancestors.get_bases().iter().cloned().collect();
564 missing_ancestors.get_bases().iter().cloned().collect();
576 as_vec.sort();
565 as_vec.sort();
577 assert_eq!(as_vec, [1, 3, 5]);
566 assert_eq!(as_vec, [1, 3, 5]);
578
567
579 missing_ancestors.add_bases([3, 7, 8].iter().cloned());
568 missing_ancestors.add_bases([3, 7, 8].iter().cloned());
580 as_vec = missing_ancestors.get_bases().iter().cloned().collect();
569 as_vec = missing_ancestors.get_bases().iter().cloned().collect();
581 as_vec.sort();
570 as_vec.sort();
582 assert_eq!(as_vec, [1, 3, 5, 7, 8]);
571 assert_eq!(as_vec, [1, 3, 5, 7, 8]);
583 }
572 }
584
573
585 fn assert_missing_remove(
574 fn assert_missing_remove(
586 bases: &[Revision],
575 bases: &[Revision],
587 revs: &[Revision],
576 revs: &[Revision],
588 expected: &[Revision],
577 expected: &[Revision],
589 ) {
578 ) {
590 let mut missing_ancestors =
579 let mut missing_ancestors =
591 MissingAncestors::new(Stub, bases.iter().cloned());
580 MissingAncestors::new(SampleGraph, bases.iter().cloned());
592 let mut revset: HashSet<Revision> = revs.iter().cloned().collect();
581 let mut revset: HashSet<Revision> = revs.iter().cloned().collect();
593 missing_ancestors
582 missing_ancestors
594 .remove_ancestors_from(&mut revset)
583 .remove_ancestors_from(&mut revset)
595 .unwrap();
584 .unwrap();
596 let mut as_vec: Vec<Revision> = revset.into_iter().collect();
585 let mut as_vec: Vec<Revision> = revset.into_iter().collect();
597 as_vec.sort();
586 as_vec.sort();
598 assert_eq!(as_vec.as_slice(), expected);
587 assert_eq!(as_vec.as_slice(), expected);
599 }
588 }
600
589
601 #[test]
590 #[test]
602 fn test_missing_remove() {
591 fn test_missing_remove() {
603 assert_missing_remove(
592 assert_missing_remove(
604 &[1, 2, 3, 4, 7],
593 &[1, 2, 3, 4, 7],
605 Vec::from_iter(1..10).as_slice(),
594 Vec::from_iter(1..10).as_slice(),
606 &[5, 6, 8, 9],
595 &[5, 6, 8, 9],
607 );
596 );
608 assert_missing_remove(&[10], &[11, 12, 13, 14], &[11, 12, 13, 14]);
597 assert_missing_remove(&[10], &[11, 12, 13, 14], &[11, 12, 13, 14]);
609 assert_missing_remove(&[7], &[1, 2, 3, 4, 5], &[3, 5]);
598 assert_missing_remove(&[7], &[1, 2, 3, 4, 5], &[3, 5]);
610 }
599 }
611
600
612 fn assert_missing_ancestors(
601 fn assert_missing_ancestors(
613 bases: &[Revision],
602 bases: &[Revision],
614 revs: &[Revision],
603 revs: &[Revision],
615 expected: &[Revision],
604 expected: &[Revision],
616 ) {
605 ) {
617 let mut missing_ancestors =
606 let mut missing_ancestors =
618 MissingAncestors::new(Stub, bases.iter().cloned());
607 MissingAncestors::new(SampleGraph, bases.iter().cloned());
619 let missing = missing_ancestors
608 let missing = missing_ancestors
620 .missing_ancestors(revs.iter().cloned())
609 .missing_ancestors(revs.iter().cloned())
621 .unwrap();
610 .unwrap();
622 assert_eq!(missing.as_slice(), expected);
611 assert_eq!(missing.as_slice(), expected);
623 }
612 }
624
613
625 #[test]
614 #[test]
626 fn test_missing_ancestors() {
615 fn test_missing_ancestors() {
627 // examples taken from test-ancestors.py by having it run
616 // examples taken from test-ancestors.py by having it run
628 // on the same graph (both naive and fast Python algs)
617 // on the same graph (both naive and fast Python algs)
629 assert_missing_ancestors(&[10], &[11], &[3, 7, 11]);
618 assert_missing_ancestors(&[10], &[11], &[3, 7, 11]);
630 assert_missing_ancestors(&[11], &[10], &[5, 10]);
619 assert_missing_ancestors(&[11], &[10], &[5, 10]);
631 assert_missing_ancestors(&[7], &[9, 11], &[3, 6, 9, 11]);
620 assert_missing_ancestors(&[7], &[9, 11], &[3, 6, 9, 11]);
632 }
621 }
633
622
634 // A Graph represented by a vector whose indices are revisions
635 // and values are parents of the revisions
636 type VecGraph = Vec<[Revision; 2]>;
637
638 impl Graph for VecGraph {
639 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
640 Ok(self[rev as usize])
641 }
642 }
643
644 /// An interesting case found by a random generator similar to
623 /// An interesting case found by a random generator similar to
645 /// the one in test-ancestor.py. An early version of Rust MissingAncestors
624 /// the one in test-ancestor.py. An early version of Rust MissingAncestors
646 /// failed this, yet none of the integration tests of the whole suite
625 /// failed this, yet none of the integration tests of the whole suite
647 /// catched it.
626 /// catched it.
648 #[test]
627 #[test]
649 fn test_remove_ancestors_from_case1() {
628 fn test_remove_ancestors_from_case1() {
650 let graph: VecGraph = vec![
629 let graph: VecGraph = vec![
651 [NULL_REVISION, NULL_REVISION],
630 [NULL_REVISION, NULL_REVISION],
652 [0, NULL_REVISION],
631 [0, NULL_REVISION],
653 [1, 0],
632 [1, 0],
654 [2, 1],
633 [2, 1],
655 [3, NULL_REVISION],
634 [3, NULL_REVISION],
656 [4, NULL_REVISION],
635 [4, NULL_REVISION],
657 [5, 1],
636 [5, 1],
658 [2, NULL_REVISION],
637 [2, NULL_REVISION],
659 [7, NULL_REVISION],
638 [7, NULL_REVISION],
660 [8, NULL_REVISION],
639 [8, NULL_REVISION],
661 [9, NULL_REVISION],
640 [9, NULL_REVISION],
662 [10, 1],
641 [10, 1],
663 [3, NULL_REVISION],
642 [3, NULL_REVISION],
664 [12, NULL_REVISION],
643 [12, NULL_REVISION],
665 [13, NULL_REVISION],
644 [13, NULL_REVISION],
666 [14, NULL_REVISION],
645 [14, NULL_REVISION],
667 [4, NULL_REVISION],
646 [4, NULL_REVISION],
668 [16, NULL_REVISION],
647 [16, NULL_REVISION],
669 [17, NULL_REVISION],
648 [17, NULL_REVISION],
670 [18, NULL_REVISION],
649 [18, NULL_REVISION],
671 [19, 11],
650 [19, 11],
672 [20, NULL_REVISION],
651 [20, NULL_REVISION],
673 [21, NULL_REVISION],
652 [21, NULL_REVISION],
674 [22, NULL_REVISION],
653 [22, NULL_REVISION],
675 [23, NULL_REVISION],
654 [23, NULL_REVISION],
676 [2, NULL_REVISION],
655 [2, NULL_REVISION],
677 [3, NULL_REVISION],
656 [3, NULL_REVISION],
678 [26, 24],
657 [26, 24],
679 [27, NULL_REVISION],
658 [27, NULL_REVISION],
680 [28, NULL_REVISION],
659 [28, NULL_REVISION],
681 [12, NULL_REVISION],
660 [12, NULL_REVISION],
682 [1, NULL_REVISION],
661 [1, NULL_REVISION],
683 [1, 9],
662 [1, 9],
684 [32, NULL_REVISION],
663 [32, NULL_REVISION],
685 [33, NULL_REVISION],
664 [33, NULL_REVISION],
686 [34, 31],
665 [34, 31],
687 [35, NULL_REVISION],
666 [35, NULL_REVISION],
688 [36, 26],
667 [36, 26],
689 [37, NULL_REVISION],
668 [37, NULL_REVISION],
690 [38, NULL_REVISION],
669 [38, NULL_REVISION],
691 [39, NULL_REVISION],
670 [39, NULL_REVISION],
692 [40, NULL_REVISION],
671 [40, NULL_REVISION],
693 [41, NULL_REVISION],
672 [41, NULL_REVISION],
694 [42, 26],
673 [42, 26],
695 [0, NULL_REVISION],
674 [0, NULL_REVISION],
696 [44, NULL_REVISION],
675 [44, NULL_REVISION],
697 [45, 4],
676 [45, 4],
698 [40, NULL_REVISION],
677 [40, NULL_REVISION],
699 [47, NULL_REVISION],
678 [47, NULL_REVISION],
700 [36, 0],
679 [36, 0],
701 [49, NULL_REVISION],
680 [49, NULL_REVISION],
702 [NULL_REVISION, NULL_REVISION],
681 [NULL_REVISION, NULL_REVISION],
703 [51, NULL_REVISION],
682 [51, NULL_REVISION],
704 [52, NULL_REVISION],
683 [52, NULL_REVISION],
705 [53, NULL_REVISION],
684 [53, NULL_REVISION],
706 [14, NULL_REVISION],
685 [14, NULL_REVISION],
707 [55, NULL_REVISION],
686 [55, NULL_REVISION],
708 [15, NULL_REVISION],
687 [15, NULL_REVISION],
709 [23, NULL_REVISION],
688 [23, NULL_REVISION],
710 [58, NULL_REVISION],
689 [58, NULL_REVISION],
711 [59, NULL_REVISION],
690 [59, NULL_REVISION],
712 [2, NULL_REVISION],
691 [2, NULL_REVISION],
713 [61, 59],
692 [61, 59],
714 [62, NULL_REVISION],
693 [62, NULL_REVISION],
715 [63, NULL_REVISION],
694 [63, NULL_REVISION],
716 [NULL_REVISION, NULL_REVISION],
695 [NULL_REVISION, NULL_REVISION],
717 [65, NULL_REVISION],
696 [65, NULL_REVISION],
718 [66, NULL_REVISION],
697 [66, NULL_REVISION],
719 [67, NULL_REVISION],
698 [67, NULL_REVISION],
720 [68, NULL_REVISION],
699 [68, NULL_REVISION],
721 [37, 28],
700 [37, 28],
722 [69, 25],
701 [69, 25],
723 [71, NULL_REVISION],
702 [71, NULL_REVISION],
724 [72, NULL_REVISION],
703 [72, NULL_REVISION],
725 [50, 2],
704 [50, 2],
726 [74, NULL_REVISION],
705 [74, NULL_REVISION],
727 [12, NULL_REVISION],
706 [12, NULL_REVISION],
728 [18, NULL_REVISION],
707 [18, NULL_REVISION],
729 [77, NULL_REVISION],
708 [77, NULL_REVISION],
730 [78, NULL_REVISION],
709 [78, NULL_REVISION],
731 [79, NULL_REVISION],
710 [79, NULL_REVISION],
732 [43, 33],
711 [43, 33],
733 [81, NULL_REVISION],
712 [81, NULL_REVISION],
734 [82, NULL_REVISION],
713 [82, NULL_REVISION],
735 [83, NULL_REVISION],
714 [83, NULL_REVISION],
736 [84, 45],
715 [84, 45],
737 [85, NULL_REVISION],
716 [85, NULL_REVISION],
738 [86, NULL_REVISION],
717 [86, NULL_REVISION],
739 [NULL_REVISION, NULL_REVISION],
718 [NULL_REVISION, NULL_REVISION],
740 [88, NULL_REVISION],
719 [88, NULL_REVISION],
741 [NULL_REVISION, NULL_REVISION],
720 [NULL_REVISION, NULL_REVISION],
742 [76, 83],
721 [76, 83],
743 [44, NULL_REVISION],
722 [44, NULL_REVISION],
744 [92, NULL_REVISION],
723 [92, NULL_REVISION],
745 [93, NULL_REVISION],
724 [93, NULL_REVISION],
746 [9, NULL_REVISION],
725 [9, NULL_REVISION],
747 [95, 67],
726 [95, 67],
748 [96, NULL_REVISION],
727 [96, NULL_REVISION],
749 [97, NULL_REVISION],
728 [97, NULL_REVISION],
750 [NULL_REVISION, NULL_REVISION],
729 [NULL_REVISION, NULL_REVISION],
751 ];
730 ];
752 let problem_rev = 28 as Revision;
731 let problem_rev = 28 as Revision;
753 let problem_base = 70 as Revision;
732 let problem_base = 70 as Revision;
754 // making the problem obvious: problem_rev is a parent of problem_base
733 // making the problem obvious: problem_rev is a parent of problem_base
755 assert_eq!(graph.parents(problem_base).unwrap()[1], problem_rev);
734 assert_eq!(graph.parents(problem_base).unwrap()[1], problem_rev);
756
735
757 let mut missing_ancestors: MissingAncestors<VecGraph> =
736 let mut missing_ancestors: MissingAncestors<VecGraph> =
758 MissingAncestors::new(
737 MissingAncestors::new(
759 graph,
738 graph,
760 [60, 26, 70, 3, 96, 19, 98, 49, 97, 47, 1, 6]
739 [60, 26, 70, 3, 96, 19, 98, 49, 97, 47, 1, 6]
761 .iter()
740 .iter()
762 .cloned(),
741 .cloned(),
763 );
742 );
764 assert!(missing_ancestors.bases.contains(&problem_base));
743 assert!(missing_ancestors.bases.contains(&problem_base));
765
744
766 let mut revs: HashSet<Revision> =
745 let mut revs: HashSet<Revision> =
767 [4, 12, 41, 28, 68, 38, 1, 30, 56, 44]
746 [4, 12, 41, 28, 68, 38, 1, 30, 56, 44]
768 .iter()
747 .iter()
769 .cloned()
748 .cloned()
770 .collect();
749 .collect();
771 missing_ancestors.remove_ancestors_from(&mut revs).unwrap();
750 missing_ancestors.remove_ancestors_from(&mut revs).unwrap();
772 assert!(!revs.contains(&problem_rev));
751 assert!(!revs.contains(&problem_rev));
773 }
752 }
774
753
775 }
754 }
@@ -1,27 +1,29 b''
1 // Copyright 2018 Georges Racinet <gracinet@anybox.fr>
1 // Copyright 2018 Georges Racinet <gracinet@anybox.fr>
2 //
2 //
3 // This software may be used and distributed according to the terms of the
3 // This software may be used and distributed according to the terms of the
4 // GNU General Public License version 2 or any later version.
4 // GNU General Public License version 2 or any later version.
5 mod ancestors;
5 mod ancestors;
6 pub use ancestors::{AncestorsIterator, LazyAncestors, MissingAncestors};
6 pub use ancestors::{AncestorsIterator, LazyAncestors, MissingAncestors};
7 #[cfg(test)]
8 pub mod testing;
7
9
8 /// Mercurial revision numbers
10 /// Mercurial revision numbers
9 ///
11 ///
10 /// As noted in revlog.c, revision numbers are actually encoded in
12 /// As noted in revlog.c, revision numbers are actually encoded in
11 /// 4 bytes, and are liberally converted to ints, whence the i32
13 /// 4 bytes, and are liberally converted to ints, whence the i32
12 pub type Revision = i32;
14 pub type Revision = i32;
13
15
14 pub const NULL_REVISION: Revision = -1;
16 pub const NULL_REVISION: Revision = -1;
15
17
16 /// The simplest expression of what we need of Mercurial DAGs.
18 /// The simplest expression of what we need of Mercurial DAGs.
17 pub trait Graph {
19 pub trait Graph {
18 /// Return the two parents of the given `Revision`.
20 /// Return the two parents of the given `Revision`.
19 ///
21 ///
20 /// Each of the parents can be independently `NULL_REVISION`
22 /// Each of the parents can be independently `NULL_REVISION`
21 fn parents(&self, Revision) -> Result<[Revision; 2], GraphError>;
23 fn parents(&self, Revision) -> Result<[Revision; 2], GraphError>;
22 }
24 }
23
25
24 #[derive(Clone, Debug, PartialEq)]
26 #[derive(Clone, Debug, PartialEq)]
25 pub enum GraphError {
27 pub enum GraphError {
26 ParentOutOfRange(Revision),
28 ParentOutOfRange(Revision),
27 }
29 }
General Comments 0
You need to be logged in to leave comments. Login now