1use std::borrow::Borrow;
2use std::collections::{HashMap, HashSet};
3use std::fmt;
4use std::hash::Hash;
5
6pub struct Graph<N, E> {
7 nodes: HashMap<N, HashMap<N, E>>,
8}
9
10impl<N: Eq + Hash + Clone, E: Default> Graph<N, E> {
11 pub fn new() -> Graph<N, E> {
12 Graph {
13 nodes: HashMap::new(),
14 }
15 }
16
17 pub fn add(&mut self, node: N) {
18 self.nodes.entry(node).or_insert_with(HashMap::new);
19 }
20
21 pub fn link(&mut self, node: N, child: N) -> &mut E {
22 self.nodes
23 .entry(node)
24 .or_insert_with(HashMap::new)
25 .entry(child)
26 .or_insert_with(Default::default)
27 }
28
29 pub fn contains<Q: ?Sized>(&self, k: &Q) -> bool
30 where
31 N: Borrow<Q>,
32 Q: Hash + Eq,
33 {
34 self.nodes.contains_key(k)
35 }
36
37 pub fn edge(&self, from: &N, to: &N) -> Option<&E> {
38 self.nodes.get(from)?.get(to)
39 }
40
41 pub fn edges(&self, from: &N) -> impl Iterator<Item = (&N, &E)> {
42 self.nodes.get(from).into_iter().flat_map(|x| x.iter())
43 }
44
45 pub fn sort(&self) -> Vec<N> {
47 let mut ret = Vec::new();
48 let mut marks = HashSet::new();
49
50 for node in self.nodes.keys() {
51 self.sort_inner_visit(node, &mut ret, &mut marks);
52 }
53
54 ret
55 }
56
57 fn sort_inner_visit(&self, node: &N, dst: &mut Vec<N>, marks: &mut HashSet<N>) {
58 if !marks.insert(node.clone()) {
59 return;
60 }
61
62 for child in self.nodes[node].keys() {
63 self.sort_inner_visit(child, dst, marks);
64 }
65
66 dst.push(node.clone());
67 }
68
69 pub fn iter(&self) -> impl Iterator<Item = &N> {
70 self.nodes.keys()
71 }
72
73 pub fn path_to_top<'a>(&'a self, mut pkg: &'a N) -> Vec<&'a N> {
76 let mut result = vec![pkg];
80 let first_pkg_depending_on = |pkg: &N, res: &[&N]| {
81 self.nodes
82 .iter()
83 .filter(|&(_, adjacent)| adjacent.contains_key(pkg))
84 .find(|&(node, _)| !res.contains(&node))
87 .map(|p| p.0)
88 };
89 while let Some(p) = first_pkg_depending_on(pkg, &result) {
90 result.push(p);
91 pkg = p;
92 }
93 result
94 }
95}
96
97impl<N: Eq + Hash + Clone, E: Default> Default for Graph<N, E> {
98 fn default() -> Graph<N, E> {
99 Graph::new()
100 }
101}
102
103impl<N: fmt::Display + Eq + Hash, E> fmt::Debug for Graph<N, E> {
104 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
105 writeln!(fmt, "Graph {{")?;
106
107 for (n, e) in &self.nodes {
108 writeln!(fmt, " - {}", n)?;
109
110 for n in e.keys() {
111 writeln!(fmt, " - {}", n)?;
112 }
113 }
114
115 write!(fmt, "}}")?;
116
117 Ok(())
118 }
119}
120
121impl<N: Eq + Hash, E: Eq> PartialEq for Graph<N, E> {
122 fn eq(&self, other: &Graph<N, E>) -> bool {
123 self.nodes.eq(&other.nodes)
124 }
125}
126impl<N: Eq + Hash, E: Eq> Eq for Graph<N, E> {}
127
128impl<N: Eq + Hash + Clone, E: Clone> Clone for Graph<N, E> {
129 fn clone(&self) -> Graph<N, E> {
130 Graph {
131 nodes: self.nodes.clone(),
132 }
133 }
134}