Skip to main content

ark/tree/
mod.rs

1
2pub mod signed;
3
4use std::cmp;
5
6/// The max radix of this tree is 4.
7const RADIX: usize = 4;
8
9#[derive(Debug, Clone)]
10pub struct Node {
11	idx: u32,
12	parent: Option<u32>,
13	children: [Option<u32>; RADIX],
14	/// Exclusive range of leaves, allowed to revolve back to 0.
15	leaves: (u32, u32),
16	nb_tree_leaves: u32,
17	level: u32,
18}
19
20impl Node {
21	fn new_leaf(idx: usize, nb_tree_leaves: usize) -> Node {
22		let idx = idx as u32;
23		Node {
24			idx,
25			parent: None,
26			children: [None; RADIX],
27			leaves: (idx, (idx+1) % nb_tree_leaves as u32),
28			nb_tree_leaves: nb_tree_leaves as u32,
29			level: 0,
30		}
31	}
32
33	pub fn idx(&self) -> usize {
34		self.idx as usize
35	}
36
37	/// The index among internal nodes, starting after the leaves
38	///
39	/// Panics if this node is a leaf node, if [Node::is_leaf] returns true.
40	pub fn internal_idx(&self) -> usize {
41		self.idx.checked_sub(self.nb_tree_leaves)
42			.expect("called internal_idx on leaf node") as usize
43	}
44
45	pub fn parent(&self) -> Option<usize> {
46		self.parent.map(|p| p as usize)
47	}
48
49	pub fn children(&self) -> impl Iterator<Item = usize> {
50		self.children.clone().into_iter().filter_map(|c| c).map(|c| c as usize)
51	}
52
53	/// The level of the node in the tree, starting with 0 for a leaf
54	pub fn level(&self) -> usize {
55		self.level as usize
56	}
57
58	/// The internal level of the node in the tree
59	///
60	/// Panics if this node is a leaf node, if [Node::is_leaf] returns true.
61	///
62	/// Returns 0 for a node  that has leaves as children
63	pub fn internal_level(&self) -> usize {
64		self.level.checked_sub(1).expect("called internal_level on leaf node") as usize
65	}
66
67	/// An iterator over all leaf indices under this node.
68	pub fn leaves(&self) -> impl Iterator<Item = usize> + Clone {
69		let (first, last) = self.leaves;
70		let nb = self.nb_tree_leaves;
71		(first..)
72			.take(nb as usize)
73			.map(move |e| e % nb)
74			.take_while(move |e| first == last || *e != last)
75			.map(|e| e as usize)
76	}
77
78	pub fn is_leaf(&self) -> bool {
79		self.children.iter().all(|o| o.is_none())
80	}
81
82	pub fn is_root(&self) -> bool {
83		self.parent.is_none()
84	}
85}
86
87//TODO(stevenroose) consider eliminating this type in favor of straight in-line iterators
88// for all nodes and for branches
89/// A radix-4 tree.
90#[derive(Debug, Clone)]
91pub struct Tree {
92	/// The nodes in the tree, starting with all the leaves
93	/// and then building up towards the root.
94	nodes: Vec<Node>,
95	nb_leaves: usize,
96}
97
98impl Tree {
99	/// Calculate the total number of nodes a tree would have
100	/// for the given number of leaves.
101	pub fn nb_nodes_for_leaves(nb_leaves: usize) -> usize {
102		let mut ret = nb_leaves;
103		let mut left = nb_leaves;
104		while left > 1 {
105			let radix = cmp::min(left, RADIX);
106			left -= radix;
107			left += 1;
108			ret += 1;
109		}
110		ret
111	}
112
113	pub fn new(
114		nb_leaves: usize,
115	) -> Tree {
116		assert_ne!(nb_leaves, 0, "trees can't be empty");
117
118		let mut nodes = Vec::with_capacity(Tree::nb_nodes_for_leaves(nb_leaves));
119
120		// First we add all the leaves to the tree.
121		nodes.extend((0..nb_leaves).map(|i| Node::new_leaf(i, nb_leaves)));
122
123		let mut cursor = 0;
124		// As long as there is more than 1 element on the leftover stack,
125		// we have to add more nodes.
126		while cursor < nodes.len() - 1 {
127			let mut children = [None; RADIX];
128			let mut nb_children = 0;
129			let mut max_child_level = 0;
130			while cursor < nodes.len() && nb_children < RADIX {
131				children[nb_children] = Some(cursor as u32);
132
133				let new_idx = nodes.len(); // idx of next node
134				let child = &mut nodes[cursor];
135				child.parent = Some(new_idx as u32);
136
137				// adjust level and leaf indices
138				if child.level > max_child_level {
139					max_child_level = child.level;
140				}
141
142				cursor += 1;
143				nb_children += 1;
144			}
145			nodes.push(Node {
146				idx: nodes.len() as u32,
147				leaves: (
148					nodes[children.first().unwrap().unwrap() as usize].leaves.0,
149					nodes[children.iter().filter_map(|c| *c).last().unwrap() as usize].leaves.1,
150				),
151				children,
152				level: max_child_level + 1,
153				parent: None,
154				nb_tree_leaves: nb_leaves as u32,
155			});
156		}
157
158		Tree { nodes, nb_leaves }
159	}
160
161	pub fn nb_leaves(&self) -> usize {
162		self.nb_leaves
163	}
164
165	pub fn nb_nodes(&self) -> usize {
166		self.nodes.len()
167	}
168
169	/// The number of internal nodes
170	pub fn nb_internal_nodes(&self) -> usize {
171		self.nodes.len().checked_sub(self.nb_leaves)
172			.expect("tree can't have less nodes than leaves")
173	}
174
175	pub fn node_at(&self, node_idx: usize) -> &Node {
176		self.nodes.get(node_idx).expect("node_idx out of bounds")
177	}
178
179	pub fn root(&self) -> &Node {
180		self.nodes.last().expect("no empty trees")
181	}
182
183	/// Iterate over all nodes, starting with the leaves, towards the root.
184	pub fn iter(&self) -> std::slice::Iter<'_, Node> {
185		self.nodes.iter()
186	}
187
188	/// Iterate over all internal nodes, starting with the ones
189	/// right beyond the leaves, towards the root.
190	pub fn iter_internal(&self) -> std::slice::Iter<'_, Node> {
191		self.nodes[self.nb_leaves..].iter()
192	}
193
194	/// Iterate over all nodes, starting with the leaves, towards the root.
195	pub fn into_iter(self) -> std::vec::IntoIter<Node> {
196		self.nodes.into_iter()
197	}
198
199	/// Iterate nodes over a branch starting at the leaf
200	/// with index `leaf_idx` ending in the root.
201	pub fn iter_branch(&self, leaf_idx: usize) -> BranchIter<'_> {
202		assert!(leaf_idx < self.nodes.len());
203		BranchIter {
204			tree: &self,
205			cursor: Some(leaf_idx),
206		}
207	}
208
209	/// Iterate over ancestors of a node with child indices.
210	///
211	/// Starting from `node_idx`, walks up towards the root. The starting node
212	/// is excluded from iteration. Each returned tuple `(ancestor_idx, child_idx)`
213	/// indicates that `child_idx` is the child position that leads back down
214	/// towards `node_idx`.
215	///
216	/// # Example
217	///
218	/// For a node 12 with children `[4, 5, 6, 7]`:
219	/// ```text
220	/// iter_branch_with_output(6) yields (12, 2), ..., (root_idx, ...)
221	/// ```
222	/// Node 6 is at child index 2 (0-indexed) of node 12.
223	pub fn iter_branch_with_output(&self, node_idx: usize) -> BranchWithOutputIter<'_> {
224		assert!(node_idx < self.nodes.len());
225		BranchWithOutputIter {
226			tree: self,
227			prev_idx: node_idx,
228			cursor: self.nodes[node_idx].parent(),
229		}
230	}
231
232	pub fn parent_idx_of(&self, idx: usize) -> Option<usize> {
233		self.nodes.get(idx).and_then(|n| n.parent.map(|c| c as usize))
234	}
235
236	/// Returns index of the the parent of the node with given `idx`,
237	/// and the index of the node among its siblings.
238	pub fn parent_idx_of_with_sibling_idx(&self, idx: usize) -> Option<(usize, usize)> {
239		self.nodes.get(idx).and_then(|n| n.parent).map(|parent_idx| {
240			let child_idx = self.nodes[parent_idx as usize].children.iter()
241				.position(|c| *c == Some(idx as u32))
242				.expect("broken tree");
243			(self.nodes[parent_idx as usize].idx as usize, child_idx as usize)
244		})
245	}
246
247}
248
249/// Iterates a tree branch.
250#[derive(Clone)]
251pub struct BranchIter<'a> {
252	tree: &'a Tree,
253	cursor: Option<usize>,
254}
255
256impl<'a> Iterator for BranchIter<'a> {
257	type Item = &'a Node;
258	fn next(&mut self) -> Option<Self::Item> {
259		if let Some(cursor) = self.cursor {
260			let ret = &self.tree.nodes[cursor];
261			self.cursor = ret.parent();
262			Some(ret)
263		} else {
264			None
265		}
266	}
267}
268
269/// Iterates ancestors of a node, returning (node_idx, child_idx) tuples.
270#[derive(Clone)]
271pub struct BranchWithOutputIter<'a> {
272	tree: &'a Tree,
273	prev_idx: usize,
274	cursor: Option<usize>,
275}
276
277impl<'a> Iterator for BranchWithOutputIter<'a> {
278	type Item = (usize, usize);
279	fn next(&mut self) -> Option<Self::Item> {
280		let cursor = self.cursor?;
281		let node = &self.tree.nodes[cursor];
282		let child_idx = node.children()
283			.position(|c| c == self.prev_idx)
284			.expect("broken tree");
285		self.prev_idx = cursor;
286		self.cursor = node.parent();
287		Some((cursor, child_idx))
288	}
289}
290
291#[cfg(test)]
292mod test {
293	use std::collections::HashSet;
294
295use super::*;
296
297	#[test]
298	fn test_simple_tree() {
299		for n in 1..100 {
300			let tree = Tree::new(n);
301
302			assert!(tree.nodes.iter().rev().skip(1).all(|n| n.parent.is_some()));
303			assert!(tree.nodes.iter().enumerate().skip(tree.nb_leaves).all(|(i, n)| {
304				n.children.iter().filter_map(|v| *v)
305					.all(|c| tree.nodes[c as usize].parent == Some(i as u32))
306			}));
307			assert!(tree.nodes.iter().enumerate().rev().skip(1).all(|(i, n)| {
308				let parent_idx = n.parent.unwrap() as usize;
309				tree.nodes[parent_idx].children.iter().find(|c| **c == Some(i as u32)).is_some()
310			}));
311			assert_eq!(Tree::nb_nodes_for_leaves(n), tree.nb_nodes(), "leaves: {}", n);
312		}
313	}
314
315	#[test]
316	fn test_leaves_range() {
317		for n in 1..42 {
318			let tree = Tree::new(n);
319
320			for node in &tree.nodes[0..tree.nb_leaves()] {
321				assert_eq!(node.leaves().collect::<Vec<_>>(), vec![node.idx()]);
322			}
323			for node in tree.iter() {
324				if !node.is_leaf() {
325					assert_eq!(
326						node.leaves().count(),
327						node.children().map(|c| tree.nodes[c].leaves().count()).sum::<usize>(),
328						"idx: {}", node.idx(),
329					);
330				}
331				assert!(node.leaves().all(|l| l < tree.nb_leaves()));
332				assert_eq!(
333					node.leaves().count(),
334					node.leaves().collect::<HashSet<_>>().len(),
335				);
336			}
337			println!("n={n} ok");
338		}
339	}
340
341	#[test]
342	fn test_iter_branch_with_output() {
343		for n in 1..100 {
344			let tree = Tree::new(n);
345
346			for start_idx in 0..tree.nb_nodes() {
347				let results: Vec<_> = tree.iter_branch_with_output(start_idx).collect();
348
349				// 1. Verify the iterator excludes the starting node
350				assert!(results.iter().all(|(idx, _)| *idx != start_idx));
351
352				// 2. Verify each returned node is an ancestor of the previous
353				let mut expected_parent = tree.nodes[start_idx].parent();
354				for (ancestor_idx, _) in &results {
355					assert_eq!(Some(*ancestor_idx), expected_parent);
356					expected_parent = tree.nodes[*ancestor_idx].parent();
357				}
358
359				// 3. Verify child_idx actually points back down the branch
360				let mut prev = start_idx;
361				for (ancestor_idx, child_idx) in &results {
362					let child = tree.nodes[*ancestor_idx].children().nth(*child_idx).unwrap();
363					assert_eq!(child, prev);
364					prev = *ancestor_idx;
365				}
366
367				// 4. Verify the last node is the root (has no parent)
368				if let Some((last_idx, _)) = results.last() {
369					assert!(tree.nodes[*last_idx].is_root());
370				}
371
372				// 5. Verify consistency with iter_branch (same path, minus starting node)
373				let branch_len = tree.iter_branch(start_idx).skip(1).count();
374				assert_eq!(results.len(), branch_len);
375			}
376		}
377	}
378}