Debian Codegraph @

crates/graph/src/lib.rs

raw symbols SCIP
1 #![allow(clippy::if_same_then_else)]
2 /// DIAGRAM of terminology
3 /// A
4 /// /\
5 /// B C
6 /// | |\
7 /// D E F
8 /// |\/| |
9 /// |/\|/
10 /// G H
11 ///
12 /// In this diagram, relative to G and H:
13 /// A, B, C, D, E are common ancestors.
14 /// C, D and E are border ancestors, because each has a non-common descendant.
15 /// D and E are least common ancestors because none of their descendants are
16 /// common ancestors.
17 /// C is not a least common ancestor because its descendant, E, is a common
18 /// ancestor.
19 ///
20 /// The find_unique_lca algorithm will pick A in two steps:
21 /// 1. find_lca('G', 'H') => ['D', 'E']
22 /// 2. Since len(['D', 'E']) > 1, find_lca('D', 'E') => ['A']
23 use std::collections::{HashMap, HashSet};
24 use std::hash::Hash;
25
26 pub mod bfs;
27 pub use bfs::BfsState;
28 pub mod graph;
29 pub use graph::{Graph, GraphError};
30 pub mod known_graph;
31 pub use known_graph::{Key, KnownGraph, MergeSortNode};
32 mod parents_provider;
33 pub use parents_provider::{
34 CachingParentsProvider, DictParentsProvider, ParentsProvider, StackedParentsProvider,
35 };
36
37 #[derive(Clone, Debug, PartialEq, Eq)]
38 pub enum Parents<K: Clone + PartialEq + Eq> {
39 Ghost,
40 Known(Vec<K>),
41 }
42
43 impl<K: Clone + PartialEq + Eq> Parents<K> {
44 pub fn is_ghost(&self) -> bool {
45 match self {
46 Parents::Ghost => true,
47 Parents::Known(_) => false,
48 }
49 }
50
51 pub fn is_known(&self) -> bool {
52 match self {
53 Parents::Ghost => false,
54 Parents::Known(_) => true,
55 }
56 }
57
58 pub fn unwrap(&self) -> Vec<K> {
59 match self {
60 Parents::Ghost => panic!("unwrap called on Ghost"),
61 Parents::Known(v) => v.clone(),
62 }
63 }
64
65 /// Borrow the known parents as a slice without cloning.
66 ///
67 /// Panics if this is a `Ghost`.
68 pub fn as_slice(&self) -> &[K] {
69 match self {
70 Parents::Ghost => panic!("as_slice called on Ghost"),
71 Parents::Known(v) => v.as_slice(),
72 }
73 }
74
75 pub fn as_ref(&self) -> Parents<&K> {
76 match self {
77 Parents::Ghost => Parents::Ghost,
78 Parents::Known(v) => Parents::Known(v.iter().collect()),
79 }
80 }
81 }
82
83 #[cfg(feature = "pyo3")]
84 impl<'py, K: pyo3::IntoPyObject<'py> + Clone + PartialEq + Eq> pyo3::IntoPyObject<'py>
85 for Parents<K>
86 {
87 type Target = pyo3::types::PyAny;
88
89 type Output = pyo3::Bound<'py, Self::Target>;
90
91 type Error = pyo3::PyErr;
92
93 fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
94 match self {
95 Parents::Ghost => Ok(py.None().into_pyobject(py)?),
96 Parents::Known(v) => Ok(pyo3::types::PyTuple::new(py, v)?.into_any()),
97 }
98 }
99 }
100
101 #[cfg(feature = "pyo3")]
102 impl<'py, K: pyo3::conversion::FromPyObjectOwned<'py> + Clone + PartialEq + Eq>
103 pyo3::FromPyObject<'_, 'py> for Parents<K>
104 {
105 type Error = pyo3::PyErr;
106
107 fn extract(obj: pyo3::Borrowed<'_, 'py, pyo3::PyAny>) -> Result<Self, Self::Error> {
108 use pyo3::prelude::*;
109 if obj.is_none() {
110 Ok(Parents::Ghost)
111 } else {
112 let v = obj.extract::<Vec<K>>()?;
113 Ok(Parents::Known(v))
114 }
115 }
116 }
117
118 #[derive(Clone, Debug, PartialEq, Eq)]
119 pub struct ParentMap<K: Hash + Clone + PartialEq + Eq>(HashMap<K, Parents<K>>);
120
121 impl<K: Clone + Hash + PartialEq + Eq> ParentMap<K> {
122 pub fn new() -> Self {
123 ParentMap(HashMap::new())
124 }
125
126 #[inline]
127 pub fn insert(&mut self, k: K, v: Parents<K>) {
128 self.0.insert(k, v);
129 }
130
131 #[inline]
132 pub fn get(&self, k: &K) -> Option<&Parents<K>> {
133 self.0.get(k)
134 }
135
136 #[inline]
137 pub fn get_key_value(&self, k: &K) -> Option<(&K, &Parents<K>)> {
138 self.0.get_key_value(k)
139 }
140
141 #[inline]
142 pub fn iter(&self) -> impl Iterator<Item = (&K, &Parents<K>)> {
143 self.0.iter()
144 }
145
146 #[inline]
147 pub fn contains_key(&self, k: &K) -> bool {
148 self.0.contains_key(k)
149 }
150
151 #[inline]
152 pub fn keys(&self) -> impl Iterator<Item = &K> {
153 self.0.keys()
154 }
155
156 #[inline]
157 pub fn values(&self) -> impl Iterator<Item = &Parents<K>> {
158 self.0.values()
159 }
160
161 #[inline]
162 pub fn len(&self) -> usize {
163 self.0.len()
164 }
165
166 #[inline]
167 pub fn remove(&mut self, k: &K) -> Option<Parents<K>> {
168 self.0.remove(k)
169 }
170
171 #[inline]
172 pub fn is_empty(&self) -> bool {
173 self.0.is_empty()
174 }
175
176 #[inline]
177 pub fn extend(&mut self, other: ParentMap<K>) {
178 self.0.extend(other.0);
179 }
180 }
181
182 impl<K: Hash + Clone + PartialEq + Eq> Default for ParentMap<K> {
183 fn default() -> Self {
184 Self::new()
185 }
186 }
187
188 impl<K: Hash + Clone + PartialEq + Eq> From<ParentMap<K>> for HashMap<K, Vec<K>> {
189 fn from(map: ParentMap<K>) -> Self {
190 map.0
191 .into_iter()
192 .map(|(k, v)| (k, v.unwrap()))
193 .collect::<HashMap<K, Vec<K>>>()
194 }
195 }
196
197 impl<K: Hash + Clone + PartialEq + Eq> From<HashMap<K, Vec<K>>> for ParentMap<K> {
198 fn from(map: HashMap<K, Vec<K>>) -> Self {
199 ParentMap(
200 map.into_iter()
201 .map(|(k, v)| (k, Parents::Known(v)))
202 .collect::<HashMap<K, Parents<K>>>(),
203 )
204 }
205 }
206
207 impl<K: Hash + Clone + PartialEq + Eq> IntoIterator for ParentMap<K> {
208 type Item = (K, Parents<K>);
209 type IntoIter = std::collections::hash_map::IntoIter<K, Parents<K>>;
210
211 fn into_iter(self) -> Self::IntoIter {
212 self.0.into_iter()
213 }
214 }
215
216 #[cfg(feature = "pyo3")]
217 impl<'py, K: pyo3::IntoPyObject<'py, Error = pyo3::PyErr> + Hash + Clone + PartialEq + Eq>
218 pyo3::IntoPyObject<'py> for ParentMap<K>
219 {
220 type Target = pyo3::types::PyDict;
221
222 type Output = pyo3::Bound<'py, Self::Target>;
223
224 type Error = pyo3::PyErr;
225
226 fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
227 use pyo3::prelude::*;
228 let dict = pyo3::types::PyDict::new(py);
229 for (k, v) in self.into_iter() {
230 dict.set_item(k, v)?;
231 }
232 Ok(dict)
233 }
234 }
235
236 #[cfg(feature = "pyo3")]
237 impl<'py, K> pyo3::FromPyObject<'_, 'py> for ParentMap<K>
238 where
239 K: for<'a> pyo3::FromPyObject<'a, 'py, Error = pyo3::PyErr> + Hash + Clone + PartialEq + Eq,
240 {
241 type Error = pyo3::PyErr;
242
243 fn extract(obj: pyo3::Borrowed<'_, 'py, pyo3::PyAny>) -> Result<Self, Self::Error> {
244 use pyo3::prelude::*;
245 let dict = obj.cast::<pyo3::types::PyDict>()?;
246 let mut result = ParentMap::new();
247 for (k, v) in dict.iter() {
248 result.insert(k.extract()?, v.extract()?);
249 }
250 Ok(result)
251 }
252 }
253
254 #[derive(Clone, Debug, PartialEq, Eq)]
255 pub struct ChildMap<K: PartialEq + Eq + Hash>(HashMap<K, Vec<K>>);
256
257 impl<K: Clone + Hash + PartialEq + Eq> Default for ChildMap<K> {
258 fn default() -> Self {
259 Self::new()
260 }
261 }
262
263 impl<K: Clone + Hash + PartialEq + Eq> ChildMap<K> {
264 pub fn new() -> Self {
265 ChildMap(HashMap::new())
266 }
267
268 #[inline]
269 pub fn insert(&mut self, k: K) {
270 self.0.entry(k).or_default();
271 }
272
273 #[inline]
274 pub fn drain(&mut self) -> impl Iterator<Item = (K, Vec<K>)> + '_ {
275 self.0.drain()
276 }
277
278 #[inline]
279 pub fn add(&mut self, k: K, v: K) {
280 self.0.entry(k).or_default().push(v);
281 }
282
283 #[inline]
284 pub fn iter(&self) -> impl Iterator<Item = (&K, &Vec<K>)> {
285 self.0.iter()
286 }
287
288 #[inline]
289 pub fn get(&self, k: &K) -> Option<&Vec<K>> {
290 self.0.get(k)
291 }
292
293 #[inline]
294 pub fn remove(&mut self, k: &K) -> Option<Vec<K>> {
295 self.0.remove(k)
296 }
297
298 #[inline]
299 pub fn is_empty(&self) -> bool {
300 self.0.is_empty()
301 }
302
303 #[inline]
304 pub fn contains_key(&self, k: &K) -> bool {
305 self.0.contains_key(k)
306 }
307 }
308
309 impl<K: Hash + Clone + Eq> std::ops::Index<&K> for ChildMap<K> {
310 type Output = Vec<K>;
311
312 fn index(&self, index: &K) -> &Self::Output {
313 &self.0[index]
314 }
315 }
316
317 impl<K: Hash + Clone + Eq> IntoIterator for ChildMap<K> {
318 type Item = (K, Vec<K>);
319 type IntoIter = std::collections::hash_map::IntoIter<K, Vec<K>>;
320
321 fn into_iter(self) -> Self::IntoIter {
322 self.0.into_iter()
323 }
324 }
325
326 #[cfg(feature = "pyo3")]
327 impl<'py, K: pyo3::IntoPyObject<'py> + Hash + Clone + PartialEq + Eq> pyo3::IntoPyObject<'py>
328 for ChildMap<K>
329 {
330 type Target = pyo3::types::PyDict;
331
332 type Output = pyo3::Bound<'py, Self::Target>;
333
334 type Error = pyo3::PyErr;
335
336 fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
337 use pyo3::prelude::*;
338 let dict = pyo3::types::PyDict::new(py);
339 for (k, v) in self.into_iter() {
340 dict.set_item(k, v)?;
341 }
342 Ok(dict)
343 }
344 }
345
346 impl<K: Hash + Clone + Eq> From<HashMap<K, Vec<K>>> for ChildMap<K> {
347 fn from(map: HashMap<K, Vec<K>>) -> Self {
348 ChildMap(map)
349 }
350 }
351
352 /// Create a child map from a parent map.
353 pub fn invert_parent_map<K: Hash + Eq + Clone>(parent_map: &ParentMap<K>) -> ChildMap<K> {
354 let mut child_map = ChildMap::new();
355 for (child, parents) in parent_map.iter() {
356 if parents.is_ghost() {
357 continue;
358 }
359 for p in parents.as_slice() {
360 child_map.add(p.clone(), child.clone());
361 }
362 }
363 child_map
364 }
365
366 impl<K> From<ParentMap<K>> for ChildMap<K>
367 where
368 K: Hash + Eq + Clone,
369 {
370 fn from(parent_map: ParentMap<K>) -> Self {
371 invert_parent_map(&parent_map)
372 }
373 }
374
375 #[cfg(test)]
376 mod invert_parent_map_tests {
377 use super::*;
378 use maplit::hashmap;
379 #[test]
380 fn test_invert() {
381 let result = super::invert_parent_map(&ParentMap::from(hashmap! {
382 2 => vec![1],
383 3 => vec![1, 2],
384 }));
385
386 // Check node 1's children (order doesn't matter)
387 let mut node1_children = result.get(&1).unwrap().clone();
388 node1_children.sort();
389 assert_eq!(vec![2, 3], node1_children);
390
391 // Check node 2's children
392 assert_eq!(vec![3], *result.get(&2).unwrap());
393
394 // Node 3 should have no children (may not be in the map)
395 assert!(result.get(&3).is_none() || result.get(&3).unwrap().is_empty());
396 }
397
398 #[test]
399 fn test_ghost() {
400 let result = super::invert_parent_map(&ParentMap::from(hashmap! {
401 2 => vec![1],
402 3 => vec![1, 2],
403 }));
404
405 // Check node 1's children (order doesn't matter)
406 let mut node1_children = result.get(&1).unwrap().clone();
407 node1_children.sort();
408 assert_eq!(vec![2, 3], node1_children);
409
410 // Check node 2's children
411 assert_eq!(vec![3], *result.get(&2).unwrap());
412 }
413 }
414
415 /// Collapse regions of the graph that are 'linear'.
416 ///
417 /// For example::
418 ///
419 /// A:[B], B:[C]
420 ///
421 /// can be collapsed by removing B and getting::
422 ///
423 /// A:[C]
424 ///
425 /// Args:
426 /// parent_map: A dictionary mapping children to their parents
427 /// Returns: Another dictionary with 'linear' chains collapsed
428 pub fn collapse_linear_regions<K: Hash + Eq + Clone>(parent_map: &ParentMap<K>) -> ParentMap<K> {
429 // Note: this isn't a strictly minimal collapse. For example:
430 // A
431 // / \
432 // B C
433 // \ /
434 // D
435 // |
436 // E
437 // Will not have 'D' removed, even though 'E' could fit. Also:
438 // A
439 // | A
440 // B => |
441 // | C
442 // C
443 // A and C are both kept because they are edges of the graph. We *could* get
444 // rid of A if we wanted.
445 // A
446 // / \
447 // B C
448 // | |
449 // D E
450 // \ /
451 // F
452 // Will not have any nodes removed, even though you do have an
453 // 'uninteresting' linear D->B and E->C
454 let mut children: HashMap<K, Vec<K>> = HashMap::new();
455 for (child, parents) in parent_map.iter() {
456 children.entry(child.clone()).or_default();
457 for p in parents.as_slice() {
458 children.entry(p.clone()).or_default().push(child.clone());
459 }
460 }
461
462 let mut removed = HashSet::new();
463 let mut result: ParentMap<K> = parent_map.clone();
464 for node in parent_map.keys() {
465 let parents = result.get(node).unwrap().as_slice();
466 if parents.len() != 1 {
467 continue;
468 }
469 let parent_children = children.get(&parents[0]).unwrap();
470 if parent_children.len() != 1 {
471 // This is not the only child
472 continue;
473 }
474 let node_children = children.get(node).unwrap();
475 if node_children.len() != 1 {
476 continue;
477 }
478 let Some(child_parents) = result.get(&node_children[0]) else {
479 continue;
480 };
481 if child_parents.as_slice().len() != 1 {
482 // This is not its only parent
483 continue;
484 }
485 // The child of this node only points at it, and the parent only has
486 // this as a child. Remove this node and splice around it.
487 let parents_owned = parents.to_vec();
488 let node_children_owned = node_children.clone();
489 result.remove(node);
490 result.insert(
491 node_children_owned[0].clone(),
492 Parents::Known(parents_owned.clone()),
493 );
494 children.insert(parents_owned[0].clone(), node_children_owned);
495 children.remove(node);
496 removed.insert(node);
497 }
498
499 result
500 }
501
502 pub mod tsort;
503
504 #[cfg(test)]
505 mod test;
506
507 #[derive(Clone, PartialEq, Eq)]
508 pub struct RevnoVec(Vec<usize>);
509
510 impl RevnoVec {
511 pub fn new() -> Self {
512 RevnoVec(vec![])
513 }
514
515 pub fn bump_last(&self) -> Self {
516 let mut ret = self.clone();
517 *ret.0.last_mut().expect("bump_last on empty RevnoVec") += 1;
518 ret
519 }
520
521 pub fn new_branch(&self, branch_count: usize) -> Self {
522 RevnoVec::from(vec![self[0], branch_count, 1])
523 }
524 }
525
526 impl Default for RevnoVec {
527 fn default() -> Self {
528 Self::new()
529 }
530 }
531
532 impl IntoIterator for RevnoVec {
533 type Item = usize;
534 type IntoIter = std::vec::IntoIter<usize>;
535
536 fn into_iter(self) -> Self::IntoIter {
537 self.0.into_iter()
538 }
539 }
540
541 impl std::ops::Index<usize> for RevnoVec {
542 type Output = usize;
543
544 fn index(&self, index: usize) -> &Self::Output {
545 &self.0[index]
546 }
547 }
548
549 impl std::ops::IndexMut<usize> for RevnoVec {
550 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
551 &mut self.0[index]
552 }
553 }
554
555 impl std::fmt::Debug for RevnoVec {
556 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
557 write!(f, "RevnoVec({:?})", self.0)
558 }
559 }
560
561 impl std::fmt::Display for RevnoVec {
562 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
563 let mut first = true;
564 for r in self.0.iter() {
565 if first {
566 first = false;
567 } else {
568 write!(f, ".")?;
569 }
570 write!(f, "{}", r)?;
571 }
572 Ok(())
573 }
574 }
575
576 impl From<Vec<usize>> for RevnoVec {
577 fn from(v: Vec<usize>) -> Self {
578 RevnoVec(v)
579 }
580 }
581
582 impl From<usize> for RevnoVec {
583 fn from(v: usize) -> Self {
584 RevnoVec(vec![v])
585 }
586 }
587
588 #[cfg(feature = "pyo3")]
589 impl<'py> pyo3::IntoPyObject<'py> for RevnoVec {
590 type Target = pyo3::types::PyTuple;
591
592 type Output = pyo3::Bound<'py, Self::Target>;
593
594 type Error = pyo3::PyErr;
595
596 fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
597 pyo3::types::PyTuple::new(py, self.0.iter())
598 }
599 }
600
601 #[cfg(feature = "pyo3")]
602 impl<'py> pyo3::FromPyObject<'_, 'py> for RevnoVec {
603 type Error = pyo3::PyErr;
604
605 fn extract(obj: pyo3::Borrowed<'_, 'py, pyo3::PyAny>) -> Result<Self, Self::Error> {
606 use pyo3::prelude::*;
607 let tuple = obj.cast::<pyo3::types::PyTuple>()?;
608 let mut ret = RevnoVec::new();
609 for r in tuple.iter() {
610 ret.0.push(r.extract()?);
611 }
612 Ok(ret)
613 }
614 }
615
616 #[derive(std::fmt::Debug)]
617 pub enum Error<K> {
618 Cycle(Vec<K>),
619 ParentMismatch {
620 key: K,
621 expected: Vec<K>,
622 actual: Vec<K>,
623 },
624 }
625
626 impl<K: std::fmt::Display> std::fmt::Display for Error<K> {
627 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
628 match self {
629 Error::Cycle(cycle) => {
630 write!(f, "Cycle: ")?;
631 let mut first = true;
632 for c in cycle.iter() {
633 if first {
634 first = false;
635 } else {
636 write!(f, " -> ")?;
637 }
638 write!(f, "{}", c)?;
639 }
640 Ok(())
641 }
642 Error::ParentMismatch {
643 key,
644 expected,
645 actual,
646 } => {
647 write!(f, "Parent mismatch for {}: ", key)?;
648 let mut first = true;
649 for e in expected.iter() {
650 if first {
651 first = false;
652 } else {
653 write!(f, ", ")?;
654 }
655 write!(f, "{}", e)?;
656 }
657 write!(f, " != ")?;
658 let mut first = true;
659 for a in actual.iter() {
660 if first {
661 first = false;
662 } else {
663 write!(f, ", ")?;
664 }
665 write!(f, "{}", a)?;
666 }
667 Ok(())
668 }
669 }
670 }
671 }
672
673 impl<K: std::fmt::Debug + std::fmt::Display> std::error::Error for Error<K> {}