id_vec/
lib.rs

1// extern crate num_traits;
2
3
4#[macro_use]
5pub mod vec;
6pub mod id;
7
8pub use vec::IdVec;
9pub use id::Id;
10
11#[cfg(test)]
12mod examples {
13    use super::*;
14
15    #[test]
16    fn nodes() {
17
18        #[derive(Debug)]
19        struct Node {
20            parent: Option<Id<Node>>,
21            name: String,
22        }
23
24
25
26        let mut nodes = IdVec::new();
27
28        let root: Id<Node> = nodes.insert(Node {
29            parent: None,
30            name: String::from("Root"),
31        });
32
33        let orphan = nodes.insert(Node {
34            parent: None,
35            name: String::from("Orphan")
36        });
37
38        let child = nodes.insert(Node {
39            parent: Some(root),
40            name: String::from("Child")
41        });
42
43        println!("{:?}", nodes);
44
45
46
47
48        // run a basic garbage collector,
49        // keeping all objects which have a parent, and the root itself
50        {
51            nodes.retain(|node_id, node|{
52                node_id == root || node.parent.is_some()
53            });
54
55            // attention! child_a was removed and thus the id becomes invalid!
56            assert!(!nodes.contains_id(orphan));
57            assert!(nodes.contains_id(root));
58            assert!(nodes.contains_id(child));
59        }
60
61
62
63        // create a cyclic graph
64        {
65            // to dereference the node, we index into the id-vec
66            let root_mut = &mut nodes[root];
67
68            // creating a cycle is possible
69            root_mut.parent = Some(child);
70        }
71    }
72
73
74    #[test]
75    fn example1() {
76        let map = id_vec!("hello", "world");
77        debug_assert!(map.contains_element(&"hello"));
78        println!("{:?}", map);
79    }
80
81    #[test]
82    fn example2() {
83        let mut words = IdVec::new();
84
85        let id_hello = words.insert("hello");
86        let _id_world = words.insert("world");
87
88        println!("{:?} -> {:?}", id_hello, words.get(id_hello));
89        assert_eq!(words.get(id_hello), Some(&"hello"));
90
91        words.remove(id_hello);
92        assert_eq!(words.get(id_hello), None);
93    }
94
95}
96