1use alloc::{rc::Rc, vec::Vec};
21use core::{cell::RefCell, fmt};
22
23#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Debug)]
25pub(crate) enum NodeRole {
26 Voter,
28 Target,
30}
31
32pub(crate) type RefCellOf<T> = Rc<RefCell<T>>;
33pub(crate) type NodeRef<A> = RefCellOf<Node<A>>;
34
35#[derive(PartialOrd, Ord, Clone, PartialEq, Eq)]
38pub(crate) struct NodeId<A> {
39 pub who: A,
41 pub role: NodeRole,
43}
44
45impl<A> NodeId<A> {
46 pub fn from(who: A, role: NodeRole) -> Self {
48 Self { who, role }
49 }
50}
51
52#[cfg(feature = "std")]
53impl<A: fmt::Debug> fmt::Debug for NodeId<A> {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 write!(
56 f,
57 "Node({:?}, {:?})",
58 self.who,
59 if self.role == NodeRole::Voter { "V" } else { "T" }
60 )
61 }
62}
63
64#[derive(Clone)]
66pub(crate) struct Node<A> {
67 pub(crate) id: NodeId<A>,
69 pub(crate) parent: Option<NodeRef<A>>,
71}
72
73impl<A: PartialEq> PartialEq for Node<A> {
74 fn eq(&self, other: &Node<A>) -> bool {
75 self.id == other.id
76 }
77}
78
79impl<A: PartialEq> Eq for Node<A> {}
80
81#[cfg(feature = "std")]
82impl<A: fmt::Debug + Clone> fmt::Debug for Node<A> {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 write!(f, "({:?} --> {:?})", self.id, self.parent.as_ref().map(|p| p.borrow().id.clone()))
85 }
86}
87
88impl<A: PartialEq + Eq + Clone + fmt::Debug> Node<A> {
89 pub fn new(id: NodeId<A>) -> Node<A> {
91 Self { id, parent: None }
92 }
93
94 pub fn is_parent_of(who: &NodeRef<A>, other: &NodeRef<A>) -> bool {
96 if who.borrow().parent.is_none() {
97 return false
98 }
99 who.borrow().parent.as_ref() == Some(other)
100 }
101
102 pub fn remove_parent(who: &NodeRef<A>) {
104 who.borrow_mut().parent = None;
105 }
106
107 pub fn set_parent_of(who: &NodeRef<A>, parent: &NodeRef<A>) {
109 who.borrow_mut().parent = Some(parent.clone());
110 }
111
112 pub fn root(start: &NodeRef<A>) -> (NodeRef<A>, Vec<NodeRef<A>>) {
122 let mut parent_path: Vec<NodeRef<A>> = Vec::new();
123 let mut visited: Vec<NodeRef<A>> = Vec::new();
124
125 parent_path.push(start.clone());
126 visited.push(start.clone());
127 let mut current = start.clone();
128
129 while let Some(ref next_parent) = current.clone().borrow().parent {
130 if visited.contains(next_parent) {
131 break
132 }
133 parent_path.push(next_parent.clone());
134 current = next_parent.clone();
135 visited.push(current.clone());
136 }
137
138 (current, parent_path)
139 }
140
141 pub fn into_ref(self) -> NodeRef<A> {
144 Rc::from(RefCell::from(self))
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 fn id(i: u32) -> NodeId<u32> {
153 NodeId::from(i, NodeRole::Target)
154 }
155
156 #[test]
157 fn basic_create_works() {
158 let node = Node::new(id(10));
159 assert_eq!(node, Node { id: NodeId { who: 10, role: NodeRole::Target }, parent: None });
160 }
161
162 #[test]
163 fn set_parent_works() {
164 let a = Node::new(id(10)).into_ref();
165 let b = Node::new(id(20)).into_ref();
166
167 assert_eq!(a.borrow().parent, None);
168 Node::set_parent_of(&a, &b);
169 assert_eq!(*a.borrow().parent.as_ref().unwrap(), b);
170 }
171
172 #[test]
173 fn get_root_singular() {
174 let a = Node::new(id(1)).into_ref();
175 assert_eq!(Node::root(&a), (a.clone(), vec![a.clone()]));
176 }
177
178 #[test]
179 fn get_root_works() {
180 let a = Node::new(id(1)).into_ref();
184 let b = Node::new(id(2)).into_ref();
185 let c = Node::new(id(3)).into_ref();
186 let d = Node::new(id(4)).into_ref();
187 let e = Node::new(id(5)).into_ref();
188 let f = Node::new(id(6)).into_ref();
189
190 Node::set_parent_of(&c, &b);
191 Node::set_parent_of(&b, &a);
192 Node::set_parent_of(&e, &a);
193 Node::set_parent_of(&a, &d);
194
195 assert_eq!(Node::root(&e), (d.clone(), vec![e.clone(), a.clone(), d.clone()]));
196
197 assert_eq!(Node::root(&a), (d.clone(), vec![a.clone(), d.clone()]));
198
199 assert_eq!(Node::root(&c), (d.clone(), vec![c.clone(), b.clone(), a.clone(), d.clone()]));
200
201 Node::set_parent_of(&a, &f);
205
206 assert_eq!(Node::root(&a), (f.clone(), vec![a.clone(), f.clone()]));
207
208 assert_eq!(Node::root(&c), (f.clone(), vec![c.clone(), b.clone(), a.clone(), f.clone()]));
209 }
210
211 #[test]
212 fn get_root_on_cycle() {
213 let a = Node::new(id(1)).into_ref();
217 let b = Node::new(id(2)).into_ref();
218 let c = Node::new(id(3)).into_ref();
219
220 Node::set_parent_of(&a, &b);
221 Node::set_parent_of(&b, &c);
222 Node::set_parent_of(&c, &a);
223
224 let (root, path) = Node::root(&a);
225 assert_eq!(root, c);
226 assert_eq!(path.clone(), vec![a.clone(), b.clone(), c.clone()]);
227 }
228
229 #[test]
230 fn get_root_on_cycle_2() {
231 let a = Node::new(id(1)).into_ref();
235 let b = Node::new(id(2)).into_ref();
236 let c = Node::new(id(3)).into_ref();
237
238 Node::set_parent_of(&a, &b);
239 Node::set_parent_of(&b, &c);
240 Node::set_parent_of(&c, &b);
241
242 let (root, path) = Node::root(&a);
243 assert_eq!(root, c);
244 assert_eq!(path.clone(), vec![a.clone(), b.clone(), c.clone()]);
245 }
246
247 #[test]
248 fn node_cmp_stack_overflows_on_non_unique_elements() {
249 let a = Node::new(id(1)).into_ref();
252 let b = Node::new(id(2)).into_ref();
253 let c = Node::new(id(3)).into_ref();
254
255 Node::set_parent_of(&a, &b);
256 Node::set_parent_of(&b, &c);
257 Node::set_parent_of(&c, &a);
258
259 Node::root(&a);
260 }
261}