1#![allow(clippy::option_map_unit_fn)]
7
8pub mod iter;
9
10use std::cell::{Ref, RefCell, RefMut};
11use std::rc::{Rc, Weak};
12
13use slotmap::{new_key_type, Key, SlotMap};
14
15new_key_type! {
16 pub struct NodeId;
17}
18
19#[derive(Debug)]
23pub struct Tree<T> {
24 root: NodeId,
25 sm: RefCell<SlotMap<NodeId, Node<T>>>,
26}
27
28#[derive(Debug, PartialEq, Eq)]
29pub struct Node<T> {
30 parent: NodeId,
31 prev_sibling: NodeId,
32 next_sibling: NodeId,
33 children: (NodeId, NodeId),
34 value: Rc<RefCell<T>>,
35}
36
37impl<T> PartialEq for Tree<T>
38where
39 T: PartialEq,
40{
41 fn eq(&self, other: &Self) -> bool {
42 self.nodes()
43 .into_iter()
44 .zip(&other.nodes())
45 .all(|((_, v1), (_, v2))| *v1.value() == *v2.value())
46 }
47}
48
49impl<T> Node<T> {
50 pub fn new(value: T) -> Self {
51 Node {
52 parent: NodeId::null(),
53 prev_sibling: NodeId::null(),
54 next_sibling: NodeId::null(),
55 children: (NodeId::null(), NodeId::null()),
56 value: Rc::new(RefCell::new(value)),
57 }
58 }
59
60 pub fn value(&self) -> Ref<'_, T> {
61 self.value.borrow()
62 }
63
64 pub fn value_mut(&self) -> RefMut<'_, T> {
65 self.value.borrow_mut()
66 }
67}
68
69impl<T> Tree<T> {
70 pub fn new(root: T) -> Rc<Self> {
72 let mut sm = SlotMap::with_key();
73 let root = sm.insert(Node::new(root));
74 Rc::new(Tree {
75 root,
76 sm: RefCell::new(sm),
77 })
78 }
79
80 pub fn with_capacity(root: T, capacity: usize) -> Rc<Self> {
82 let mut sm = SlotMap::with_capacity_and_key(capacity);
83 let root = sm.insert(Node::new(root));
84 Rc::new(Tree {
85 root,
86 sm: RefCell::new(sm),
87 })
88 }
89
90 pub fn get(self: &Rc<Self>, id: NodeId) -> Option<NodeRef<T>> {
92 self.sm.borrow().get(id).map(|_node| NodeRef {
93 id,
94 tree: Rc::downgrade(self),
95 })
96 }
97
98 pub fn root(self: &Rc<Self>) -> NodeRef<T> {
100 self.get(self.root).unwrap()
101 }
102
103 pub fn orphan(self: &Rc<Self>, value: T) -> NodeId {
105 self.sm.borrow_mut().insert(Node::new(value))
106 }
107}
108
109#[derive(Debug)]
111pub struct NodeRef<T> {
112 id: NodeId,
113 tree: Weak<Tree<T>>,
114}
115
116impl<T> Clone for NodeRef<T> {
117 fn clone(&self) -> Self {
118 Self {
119 id: self.id,
120 tree: self.tree.clone(),
121 }
122 }
123}
124
125impl<T> PartialEq for NodeRef<T> {
126 fn eq(&self, other: &Self) -> bool {
127 self.id == other.id
128 && self.tree.strong_count() > 0
129 && other.tree.strong_count() > 0
130 && self.tree.upgrade().map(|rc| &*rc as *const _)
131 == other.tree.upgrade().map(|rc| &*rc as *const _)
132 }
133}
134
135impl<T> NodeRef<T> {
136 pub fn id(&self) -> NodeId {
138 self.id
139 }
140
141 pub fn map_value<F, R>(&self, map_fn: F) -> Option<R>
143 where
144 F: FnOnce(&T) -> R,
145 {
146 self.tree.upgrade().and_then(|tree| {
147 tree.sm
148 .borrow()
149 .get(self.id)
150 .map(|node| map_fn(&node.value.borrow()))
151 })
152 }
153
154 pub fn update_value<F>(&self, update_fn: F) -> bool
156 where
157 F: FnOnce(&mut T),
158 {
159 self.tree
160 .upgrade()
161 .and_then(|tree| {
162 tree.sm.borrow().get(self.id).map(|node| {
163 update_fn(&mut node.value.borrow_mut());
164 true
165 })
166 })
167 .unwrap_or(false)
168 }
169
170 pub fn parent(&self) -> Option<Self> {
172 self.tree.upgrade().and_then(|tree| {
173 tree.sm
174 .borrow()
175 .get(self.id)
176 .and_then(|node| tree.get(node.parent))
177 })
178 }
179
180 pub fn prev_sibling(&self) -> Option<Self> {
182 self.tree.upgrade().and_then(|tree| {
183 tree.sm
184 .borrow()
185 .get(self.id)
186 .and_then(|node| tree.get(node.prev_sibling))
187 })
188 }
189
190 pub fn next_sibling(&self) -> Option<Self> {
192 self.tree.upgrade().and_then(|tree| {
193 tree.sm
194 .borrow()
195 .get(self.id)
196 .and_then(|node| tree.get(node.next_sibling))
197 })
198 }
199
200 pub fn first_child(&self) -> Option<Self> {
202 self.tree.upgrade().and_then(|tree| {
203 tree.sm
204 .borrow()
205 .get(self.id)
206 .and_then(|node| tree.get(node.children.0))
207 })
208 }
209
210 pub fn last_child(&self) -> Option<Self> {
212 self.tree.upgrade().and_then(|tree| {
213 tree.sm
214 .borrow()
215 .get(self.id)
216 .and_then(|node| tree.get(node.children.1))
217 })
218 }
219
220 pub fn has_siblings(&self) -> bool {
222 self.tree
223 .upgrade()
224 .map(|tree| {
225 tree.sm
226 .borrow()
227 .get(self.id)
228 .map(|node| !node.prev_sibling.is_null() || !node.next_sibling.is_null())
229 .unwrap_or(false)
230 })
231 .unwrap_or(false)
232 }
233
234 pub fn has_children(&self) -> bool {
236 self.tree
237 .upgrade()
238 .map(|tree| {
239 tree.sm
240 .borrow()
241 .get(self.id)
242 .map(|node| !node.children.0.is_null() && !node.children.1.is_null())
243 .unwrap_or(false)
244 })
245 .unwrap_or(false)
246 }
247
248 pub fn detach(&mut self) {
250 self.tree.upgrade().map(|tree| {
251 let (parent_id, prev_sibling_id, next_sibling_id) = tree
252 .sm
253 .borrow()
254 .get(self.id)
255 .map(|node| (node.parent, node.prev_sibling, node.next_sibling))
256 .unwrap_or((NodeId::null(), NodeId::null(), NodeId::null()));
257
258 if !parent_id.is_null() {
259 tree.sm.borrow_mut().get_mut(self.id).map(|node| {
260 node.parent = NodeId::null();
261 node.prev_sibling = NodeId::null();
262 node.next_sibling = NodeId::null();
263 });
264 } else {
265 return;
266 }
267
268 if !prev_sibling_id.is_null() {
269 tree.sm
270 .borrow_mut()
271 .get_mut(prev_sibling_id)
272 .map(|node| node.next_sibling = next_sibling_id);
273 }
274
275 if !next_sibling_id.is_null() {
276 tree.sm
277 .borrow_mut()
278 .get_mut(next_sibling_id)
279 .map(|node| node.prev_sibling = prev_sibling_id);
280 }
281
282 tree.sm.borrow_mut().get_mut(parent_id).map(|parent| {
283 let (first_child_id, last_child_id) = parent.children;
284 if first_child_id == last_child_id {
285 parent.children = (NodeId::null(), NodeId::null());
286 } else if first_child_id == self.id {
287 parent.children = (next_sibling_id, last_child_id);
288 } else if last_child_id == self.id {
289 parent.children = (first_child_id, prev_sibling_id);
290 }
291 });
292 });
293 }
294
295 pub fn append(&mut self, value: T) -> Option<NodeRef<T>> {
297 self.tree.upgrade().and_then(|tree| {
298 let new_child_id = tree.orphan(value);
299 self.append_id(new_child_id)
300 })
301 }
302
303 pub fn append_id(&mut self, new_child_id: NodeId) -> Option<NodeRef<T>> {
305 self.tree.upgrade().and_then(|tree| {
306 let last_child_id = self
307 .last_child()
308 .map(|child| child.id)
309 .unwrap_or_else(NodeId::null);
310
311 tree.sm.borrow_mut().get_mut(new_child_id).map(|new_child| {
312 new_child.parent = self.id;
313 new_child.prev_sibling = last_child_id;
314 });
315
316 tree.sm
317 .borrow_mut()
318 .get_mut(last_child_id)
319 .map(|last_child| {
320 last_child.next_sibling = new_child_id;
321 });
322
323 tree.sm.borrow_mut().get_mut(self.id).map(|this_node| {
324 if !this_node.children.0.is_null() {
325 this_node.children.1 = new_child_id;
326 } else {
327 this_node.children.0 = new_child_id;
328 this_node.children.1 = new_child_id;
329 }
330 });
331
332 tree.get(new_child_id)
333 })
334 }
335
336 pub fn prepend(&mut self, value: T) -> Option<NodeRef<T>> {
338 self.tree.upgrade().and_then(|tree| {
339 let new_child_id = tree.orphan(value);
340
341 let first_child_id = self
342 .first_child()
343 .map(|child| child.id)
344 .unwrap_or_else(NodeId::null);
345
346 tree.sm.borrow_mut().get_mut(new_child_id).map(|new_child| {
347 new_child.parent = self.id;
348 new_child.next_sibling = first_child_id;
349 });
350
351 tree.sm
352 .borrow_mut()
353 .get_mut(first_child_id)
354 .map(|first_child| {
355 first_child.prev_sibling = new_child_id;
356 });
357
358 tree.sm.borrow_mut().get_mut(self.id).map(|this_node| {
359 if !this_node.children.1.is_null() {
360 this_node.children.0 = new_child_id;
361 } else {
362 this_node.children.0 = new_child_id;
363 this_node.children.1 = new_child_id;
364 }
365 });
366
367 tree.get(new_child_id)
368 })
369 }
370
371 pub fn insert_before(&mut self, value: T) -> Option<NodeRef<T>> {
373 self.tree.upgrade().and_then(|tree| {
374 let new_sibling_id = tree.orphan(value);
375 self.insert_id_before(new_sibling_id)
376 })
377 }
378
379 pub fn insert_id_before(&mut self, new_sibling_id: NodeId) -> Option<NodeRef<T>> {
381 self.tree
382 .upgrade()
383 .zip(self.parent())
384 .and_then(|(tree, parent)| {
385 let prev_sibling_id = self
386 .prev_sibling()
387 .map(|prev_sibling| prev_sibling.id)
388 .unwrap_or_else(NodeId::null);
389
390 tree.sm
391 .borrow_mut()
392 .get_mut(new_sibling_id)
393 .map(|new_sibling| {
394 new_sibling.parent = parent.id;
395 new_sibling.prev_sibling = prev_sibling_id;
396 new_sibling.next_sibling = self.id;
397 });
398
399 tree.sm
400 .borrow_mut()
401 .get_mut(prev_sibling_id)
402 .map(|prev_sibling| {
403 prev_sibling.next_sibling = new_sibling_id;
404 });
405
406 tree.sm.borrow_mut().get_mut(self.id).map(|this_node| {
407 this_node.prev_sibling = new_sibling_id;
408 });
409
410 tree.sm.borrow_mut().get_mut(parent.id).map(|parent| {
411 if parent.children.0 == self.id {
412 parent.children.0 = new_sibling_id;
413 }
414 });
415
416 tree.get(new_sibling_id)
417 })
418 }
419
420 pub fn insert_after(&mut self, value: T) -> Option<NodeRef<T>> {
422 self.tree.upgrade().and_then(|tree| {
423 let new_sibling_id = tree.orphan(value);
424 self.insert_id_after(new_sibling_id)
425 })
426 }
427
428 pub fn insert_id_after(&mut self, new_sibling_id: NodeId) -> Option<NodeRef<T>> {
430 self.tree
431 .upgrade()
432 .zip(self.parent())
433 .and_then(|(tree, parent)| {
434 let next_sibling_id = self
435 .next_sibling()
436 .map(|next_sibling| next_sibling.id)
437 .unwrap_or_else(NodeId::null);
438
439 tree.sm
440 .borrow_mut()
441 .get_mut(new_sibling_id)
442 .map(|new_sibling| {
443 new_sibling.parent = parent.id;
444 new_sibling.prev_sibling = self.id;
445 new_sibling.next_sibling = next_sibling_id;
446 });
447
448 tree.sm
449 .borrow_mut()
450 .get_mut(next_sibling_id)
451 .map(|next_sibling| {
452 next_sibling.prev_sibling = new_sibling_id;
453 });
454
455 tree.sm.borrow_mut().get_mut(self.id).map(|this_node| {
456 this_node.next_sibling = new_sibling_id;
457 });
458
459 tree.sm.borrow_mut().get_mut(parent.id).map(|parent| {
460 if parent.children.1 == self.id {
461 parent.children.1 = new_sibling_id;
462 }
463 });
464
465 tree.get(new_sibling_id)
466 })
467 }
468
469 pub fn reparent_from_id_append(&mut self, from_id: NodeId) {
471 self.tree.upgrade().map(|tree| {
472 let new_child_ids = tree
473 .sm
474 .borrow_mut()
475 .get_mut(from_id)
476 .map(|node| {
477 let new_child_ids = node.children;
478 node.children = (NodeId::null(), NodeId::null());
479 new_child_ids
480 })
481 .unwrap_or((NodeId::null(), NodeId::null()));
482
483 if new_child_ids.0.is_null() && new_child_ids.1.is_null() {
484 return;
485 }
486
487 tree.sm.borrow_mut().get_mut(new_child_ids.0).map(|node| {
488 node.parent = self.id;
489 });
490 tree.sm.borrow_mut().get_mut(new_child_ids.1).map(|node| {
491 node.parent = self.id;
492 });
493
494 let old_child_ids = tree.sm.borrow_mut().get_mut(self.id).and_then(|node| {
495 if node.children.0.is_null() && node.children.1.is_null() {
496 node.children = new_child_ids;
497 None
498 } else {
499 Some(node.children)
500 }
501 });
502 let old_child_ids = match old_child_ids {
503 Some(old_child_ids) => old_child_ids,
504 None => return,
505 };
506
507 tree.sm.borrow_mut().get_mut(old_child_ids.1).map(|node| {
508 node.next_sibling = new_child_ids.0;
509 });
510 tree.sm.borrow_mut().get_mut(new_child_ids.0).map(|node| {
511 node.prev_sibling = old_child_ids.1;
512 });
513
514 tree.sm
515 .borrow_mut()
516 .get_mut(self.id)
517 .map(|node| node.children = (old_child_ids.0, new_child_ids.1));
518 });
519 }
520}
521
522#[macro_export]
549macro_rules! tree {
550 (@ $n:ident { }) => { };
551
552 (@ $n:ident { $value:expr }) => {
554 { $n.append($value).unwrap(); }
555 };
556
557 (@ $n:ident { $value:expr, $($tail:tt)* }) => {
559 {
560 $n.append($value).unwrap();
561 tree!(@ $n { $($tail)* });
562 }
563 };
564
565 (@ $n:ident { $value:expr => $children:tt }) => {
567 {
568 let mut node = $n.append($value).unwrap();
569 tree!(@ node $children);
570 }
571 };
572
573 (@ $n:ident { $value:expr => $children:tt, $($tail:tt)* }) => {
575 {
576 {
577 let mut node = $n.append($value).unwrap();
578 tree!(@ node $children);
579 }
580 tree!(@ $n { $($tail)* });
581 }
582 };
583
584 ($root:expr) => { $crate::Tree::new($root) };
585
586 ($root:expr => $children:tt) => {
587 {
588 let tree = $crate::Tree::new($root);
589 {
590 let mut node = tree.root();
591 tree!(@ node $children);
592 }
593 tree
594 }
595 };
596}