1use std::fmt::{Debug, Display, Formatter};
2use std::num::NonZeroUsize;
3
4use crate::iter::*;
5use crate::prelude::*;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct NodeId(NonZeroUsize);
15
16impl NodeId {
17 pub fn from_index(n: usize) -> Self {
18 NodeId(NonZeroUsize::new(n + 1).unwrap())
19 }
20
21 pub fn to_index(self) -> usize {
22 self.0.get() - 1
23 }
24}
25
26impl Display for NodeId {
27 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
28 write! {f, "NodeId({})", self.0}
29 }
30}
31
32impl From<usize> for NodeId {
33 fn from(x: usize) -> Self {
34 NodeId::from_index(x)
35 }
36}
37
38impl From<NodeId> for usize {
39 fn from(x: NodeId) -> Self {
40 x.to_index()
41 }
42}
43
44#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
46pub struct Node<'a, T: 'a> {
47 pub id: NodeId,
49 pub data: &'a T,
51 pub(crate) tree: &'a Tree<T>,
53}
54
55impl<T: Debug> Node<'_, T> {
56 pub fn level(&self) -> usize {
57 self.tree.level[self.id.to_index()]
58 }
59 pub fn parent(&self) -> usize {
60 self.tree.parent[self.id.to_index()]
61 }
62
63 pub fn parents(&self) -> ParentIter<'_, T> {
65 ParentIter {
66 parent: self.parent(),
67 node: self.id,
68 tree: self.tree,
69 }
70 }
71
72 pub fn children(&self) -> ChildrenIter<'_, T> {
74 ChildrenIter::new(self.id, self.tree)
75 }
76
77 pub fn siblings(&self) -> SiblingsIter<'_, T> {
79 SiblingsIter {
80 pos: 0,
81 level: self.level(),
82 node: self.id,
83 tree: self.tree,
84 }
85 }
86}
87
88impl<T: Debug> Debug for Node<'_, T> {
89 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
90 write! {f, "{:?}:{:?}", self.id, self.data}
91 }
92}
93
94impl<T: Display> Display for Node<'_, T> {
95 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
96 write! {f, "{}", self.data}
97 }
98}
99
100#[derive(PartialEq, Eq, PartialOrd, Ord)]
102pub struct NodeMut<'a, T: 'a> {
103 pub id: NodeId,
105 pub data: &'a mut T,
107}
108
109impl<T: Debug> Debug for NodeMut<'_, T> {
110 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
111 write! {f, "{:?}:{:?}", self.id, self.data}
112 }
113}
114
115impl<T: Display> Display for NodeMut<'_, T> {
116 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
117 write! {f, "{}", self.data}
118 }
119}
120
121#[derive(Debug)]
123pub struct TreeMut<'a, T: 'a> {
124 pub id: NodeId,
126 pub parent: NodeId,
128 pub tree: &'a mut Tree<T>,
130}
131
132impl<'a, T: Debug + 'a> TreeMut<'a, T> {
133 pub fn get_parent_level(&self) -> usize {
134 self.tree.get_level(self.parent)
135 }
136
137 pub fn push(&mut self, data: T) -> TreeMut<T>
140 where
141 T: Debug,
142 {
143 let id = self.append(data);
144 self.tree._make_tree_mut(id, id)
145 }
146
147 pub fn append(&mut self, data: T) -> NodeId
150 where
151 T: Debug,
152 {
153 let level = self.get_parent_level() + 1;
154
155 self.tree.push_with_level(data, level, self.parent)
156 }
157}