safe_graph/
node.rs

1//! Graph Node related constructs.
2
3use crate::edge::CompactDirection;
4use indexmap::map::Keys;
5use std::fmt::Debug;
6use std::hash::Hash;
7use std::iter::Cloned;
8
9/// A trait group for `Graph`'s node identifier.
10pub trait NodeTrait: Copy + Debug + Hash + Ord {}
11
12/// Implement the `NodeTrait` for all types satisfying bounds.
13impl<N> NodeTrait for N where N: Copy + Debug + Hash + Ord {}
14
15/// Iterator over Nodes.
16pub struct Nodes<'a, N: 'a + NodeTrait> {
17    iter: Cloned<Keys<'a, N, Vec<(N, CompactDirection)>>>,
18}
19
20impl<'a, N: 'a + NodeTrait> Nodes<'a, N> {
21    pub fn new(iter: Cloned<Keys<'a, N, Vec<(N, CompactDirection)>>>) -> Self {
22        Self { iter }
23    }
24}
25
26impl<'a, N: 'a + NodeTrait> Iterator for Nodes<'a, N> {
27    type Item = N;
28    #[inline]
29    fn next(&mut self) -> Option<Self::Item> {
30        self.iter.next()
31    }
32
33    #[inline]
34    fn size_hint(&self) -> (usize, Option<usize>) {
35        self.iter.size_hint()
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use crate::edge::CompactDirection;
42    use crate::node::Nodes;
43    use indexmap::IndexMap;
44
45    #[test]
46    fn new() {
47        let nodes: IndexMap<i32, Vec<(i32, CompactDirection)>> = IndexMap::new();
48
49        Nodes::new(nodes.keys().cloned());
50    }
51
52    #[test]
53    fn next() {
54        let mut nodes: IndexMap<i32, Vec<(i32, CompactDirection)>> = IndexMap::with_capacity(3);
55        nodes.insert(1, vec![]);
56        nodes.insert(2, vec![]);
57        nodes.insert(3, vec![]);
58
59        let mut nodes = Nodes::new(nodes.keys().cloned());
60
61        // Test node `1`.
62        assert_eq!(nodes.next(), Some(1));
63        assert_eq!(nodes.next(), Some(2));
64        assert_eq!(nodes.next(), Some(3));
65
66        // Test the end of iteration.
67        assert_eq!(nodes.next(), None);
68    }
69
70    #[test]
71    fn size_hint() {
72        let mut nodes: IndexMap<i32, Vec<(i32, CompactDirection)>> = IndexMap::with_capacity(3);
73        nodes.insert(1, vec![]);
74        nodes.insert(2, vec![]);
75        nodes.insert(3, vec![]);
76
77        let mut nodes = Nodes::new(nodes.keys().cloned());
78
79        assert_eq!(nodes.size_hint(), (3, Some(3)));
80
81        // Lower the length of the iterator.
82        nodes.next();
83
84        assert_eq!(nodes.size_hint(), (2, Some(2)));
85
86        // Lower the length of the iterator.
87        nodes.next();
88
89        assert_eq!(nodes.size_hint(), (1, Some(1)));
90
91        // Lower the length of the iterator.
92        nodes.next();
93
94        assert_eq!(nodes.size_hint(), (0, Some(0)));
95    }
96}