rc_graph/
rc_graph.rs

1use index_alloc::rc::{Rc, Weak};
2use index_alloc::IndexAllocator;
3
4const MEMORY_SIZE: usize = 1024;
5const INDEX_SIZE: usize = 64;
6
7#[derive(Clone)]
8pub enum Link<'a, T> {
9    Held(Rc<'a, Node<'a, T>, MEMORY_SIZE, INDEX_SIZE>),
10    Weak(Weak<'a, Node<'a, T>, MEMORY_SIZE, INDEX_SIZE>),
11}
12
13impl<'a, T> Link<'a, T> {
14    fn new_held(node: Rc<'a, Node<'a, T>, MEMORY_SIZE, INDEX_SIZE>) -> Self {
15        Self::Held(node)
16    }
17
18    fn new_weak(node: Weak<'a, Node<'a, T>, MEMORY_SIZE, INDEX_SIZE>) -> Self {
19        Self::Weak(node)
20    }
21
22    fn to(&self) -> Option<Rc<'a, Node<'a, T>, MEMORY_SIZE, INDEX_SIZE>> {
23        match self {
24            Self::Held(rc) => Some(rc.clone()),
25            Self::Weak(weak) => weak.upgrade(),
26        }
27    }
28}
29
30pub struct Node<'a, T> {
31    val: T,
32    links: [Option<Link<'a, T>>; 4],
33}
34
35impl<'a, T> Node<'a, T> {
36    fn new(val: T) -> Self {
37        Self {
38            val,
39            links: [None, None, None, None],
40        }
41    }
42
43    fn add_link(&mut self, link: Link<'a, T>) {
44        for l in self.links.iter_mut() {
45            if matches!(l, None) {
46                *l = Some(link);
47                return;
48            }
49        }
50        panic!("No more links available");
51    }
52
53    fn iter_links(&self) -> impl Iterator<Item = &Link<'a, T>> {
54        self.links.iter().filter_map(move |l| l.as_ref())
55    }
56}
57
58fn main() {
59    let allocator: IndexAllocator<1024, 64> = IndexAllocator::empty();
60
61    let mut main_node = Node::new("Main");
62    let first_child_node = Rc::try_new(Node::new("First child node"), &allocator).unwrap();
63
64    let second_child_node = {
65        let mut node = Node::new("Second child node");
66        node.add_link(Link::Weak(first_child_node.downgrade()));
67        Rc::try_new(node, &allocator).unwrap()
68    };
69
70    main_node.add_link(Link::new_held(first_child_node.clone()));
71    main_node.add_link(Link::new_held(second_child_node.clone()));
72
73    for l in main_node.iter_links() {
74        println!("Main node is linked to : {}", l.to().unwrap().val);
75    }
76
77    for l in second_child_node.iter_links() {
78        println!("Second child node is linked to : {}", l.to().unwrap().val);
79    }
80}