1use std::{fmt::Debug, iter::Iterator, marker::PhantomData};
2
3#[cfg(test)]
4mod tests;
5
6pub struct Node<K, V> {
9 pub value: V,
11 parent: usize,
13 num_descendants: usize,
16 _key_type: PhantomData<K>,
19}
20
21impl<K, V> Node<K, V>
22where
23 usize: Into<K>,
24{
25 pub fn parent(&self) -> K {
28 self.parent.into()
29 }
30
31 pub fn num_descendants(&self) -> usize {
33 self.num_descendants
34 }
35}
36
37impl<K, V: Debug> Debug for Node<K, V> {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 f.debug_struct("Node")
40 .field("value", &self.value)
41 .field("parent", &self.parent)
42 .field("num_descendants", &self.num_descendants)
43 .finish()
44 }
45}
46
47impl<K, V: PartialEq> PartialEq for Node<K, V> {
48 fn eq(&self, other: &Self) -> bool {
49 self.value == other.value
50 && self.parent == other.parent
51 && self.num_descendants == other.num_descendants
52 }
53}
54
55impl<K, V: Clone> Clone for Node<K, V> {
56 fn clone(&self) -> Self {
57 Self {
58 value: self.value.clone(),
59 parent: self.parent.clone(),
60 num_descendants: self.num_descendants.clone(),
61 _key_type: PhantomData,
62 }
63 }
64}
65
66impl<K, V: Eq> Eq for Node<K, V> {}
67
68impl<K, V: Copy> Copy for Node<K, V> {}
69
70pub struct Tree<K, V> {
72 nodes: Vec<Node<K, V>>,
73 parent_stack: Vec<usize>,
74}
75
76impl<K, V> Default for Tree<K, V> {
77 fn default() -> Self {
78 Self {
79 nodes: Default::default(),
80 parent_stack: Default::default(),
81 }
82 }
83}
84
85impl<K, V> Tree<K, V>
86where
87 usize: Into<K>,
88 K: Into<usize>,
89{
90 pub fn new() -> Self {
92 Self::default()
93 }
94
95 pub fn with_capacity(capacity: usize) -> Self {
97 Self {
98 nodes: Vec::with_capacity(capacity),
99 parent_stack: Vec::new(),
100 }
101 }
102
103 pub fn len(&self) -> usize {
105 self.nodes.len()
106 }
107
108 pub fn is_empty(&self) -> bool {
110 self.nodes.is_empty()
111 }
112
113 pub fn push(&mut self, value: V) -> K {
121 let id = self.len();
122
123 self.nodes.push(Node {
124 value,
125 parent: *self.parent_stack.last().unwrap_or(&id),
126 num_descendants: 0,
127 _key_type: PhantomData,
128 });
129
130 for &parent in self.parent_stack.iter() {
132 self.nodes[parent].num_descendants += 1;
133 }
134
135 self.parent_stack.push(id);
136
137 id.into()
138 }
139
140 pub fn up(&mut self) -> Option<K> {
150 self.parent_stack.pop();
151 self.parent_stack.last().map(|&id| id.into())
152 }
153
154 pub fn get(&self, id: K) -> Option<&Node<K, V>> {
156 self.nodes.get(id.into())
157 }
158
159 pub fn get_mut(&mut self, id: K) -> Option<&mut Node<K, V>> {
161 self.nodes.get_mut(id.into())
162 }
163
164 pub fn first(&self) -> Option<&Node<K, V>> {
168 self.nodes.first()
169 }
170
171 pub fn first_mut(&mut self) -> Option<&mut Node<K, V>> {
175 self.nodes.first_mut()
176 }
177
178 pub fn last(&self) -> Option<&Node<K, V>> {
182 self.nodes.last()
183 }
184
185 pub fn last_mut(&mut self) -> Option<&mut Node<K, V>> {
189 self.nodes.last_mut()
190 }
191
192 pub fn iter(&self) -> impl Iterator<Item = &Node<K, V>> {
195 self.nodes.iter()
196 }
197
198 pub fn into_iter(self) -> impl Iterator<Item = Node<K, V>> {
201 self.nodes.into_iter()
202 }
203
204 pub fn all(&self) -> &[Node<K, V>] {
207 self.nodes.as_slice()
208 }
209
210 pub fn descendents(&self, id: K) -> &[Node<K, V>] {
212 let id = id.into();
213 let num_descendants = self
214 .nodes
215 .get(id)
216 .map(|node| node.num_descendants)
217 .unwrap_or_default();
218 &self.nodes[id + 1..id + 1 + num_descendants]
219 }
220
221 pub fn parents(&self, id: K) -> ParentIter<'_, K, V> {
223 let id = id.into();
224 ParentIter { id, tree: self }
225 }
226
227 pub fn children(&self, id: K) -> ChildrenIter<'_, K, V> {
229 let id = id.into();
230 ChildrenIter {
231 current_id: id + 1,
232 max_id: id
233 + self
234 .nodes
235 .get(id)
236 .map(|node| node.num_descendants)
237 .unwrap_or_default(),
238 tree: self,
239 }
240 }
241}
242
243impl<K, V: Debug> Debug for Tree<K, V> {
244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245 f.debug_struct("Tree")
246 .field("nodes", &self.nodes)
247 .field("parent_stack", &self.parent_stack)
248 .finish()
249 }
250}
251
252impl<K, V: PartialEq> PartialEq for Tree<K, V> {
253 fn eq(&self, other: &Self) -> bool {
254 self.nodes == other.nodes && self.parent_stack == other.parent_stack
255 }
256}
257
258impl<K, V: Clone> Clone for Tree<K, V> {
259 fn clone(&self) -> Self {
260 Self {
261 nodes: self.nodes.clone(),
262 parent_stack: self.parent_stack.clone(),
263 }
264 }
265}
266
267impl<K, V: Eq> Eq for Tree<K, V> {}
268
269pub struct ParentIter<'a, K, V> {
270 id: usize,
271 tree: &'a Tree<K, V>,
272}
273
274impl<'a, K, V> Iterator for ParentIter<'a, K, V>
275where
276 K: Into<usize>,
277 usize: Into<K>,
278{
279 type Item = (K, &'a Node<K, V>);
280
281 fn next(&mut self) -> Option<Self::Item> {
282 self.tree.nodes.get(self.id).and_then(|node| {
283 if node.parent == self.id {
284 None
285 } else {
286 self.id = node.parent;
287 self.tree
288 .nodes
289 .get(self.id)
290 .map(|node| (self.id.into(), node))
291 }
292 })
293 }
294}
295
296pub struct ChildrenIter<'a, K, V> {
297 current_id: usize,
298 max_id: usize,
299 tree: &'a Tree<K, V>,
300}
301
302impl<'a, K, V> Iterator for ChildrenIter<'a, K, V>
303where
304 usize: Into<K>,
305{
306 type Item = (K, &'a Node<K, V>);
307
308 fn next(&mut self) -> Option<Self::Item> {
309 if self.current_id <= self.max_id {
310 let node = self.tree.nodes.get(self.current_id);
311 let id_and_node = node.map(|node| (self.current_id.into(), node));
312 self.current_id += self
313 .tree
314 .nodes
315 .get(self.current_id)
316 .map(|node| node.num_descendants)
317 .unwrap_or_default()
318 + 1;
319 id_and_node
320 } else {
321 None
322 }
323 }
324}