#[cfg(feature = "async")]
mod r#async;
#[cfg(feature = "async")]
pub use r#async::*;
#[cfg(not(feature = "async"))]
mod sync;
#[cfg(not(feature = "async"))]
pub use sync::*;
mod macros {
#[macro_export]
macro_rules! node {
($value:expr $(,$($children:expr),*)?) => (
Node {
value: $value,
children: vec![ $($($children),*)? ]
}
)
}
}
#[derive(Debug)]
pub struct Node<T> {
value: T,
children: Vec<Node<T>>,
}
impl<T> Node<T> {
pub fn new(value: T) -> Self {
Node {
value,
children: vec![],
}
}
pub fn value(&self) -> &T {
&self.value
}
pub fn set_value(&mut self, value: T) {
self.value = value;
}
pub fn value_mut(&mut self) -> &mut T {
&mut self.value
}
pub fn children(&self) -> &[Node<T>] {
&self.children
}
pub fn children_mut(&mut self) -> &mut [Node<T>] {
self.children.as_mut()
}
pub fn add_child(&mut self, child: Node<T>) -> usize {
self.children.push(child);
self.children.len()
}
pub fn remove_child(&mut self, index: usize) -> Option<Node<T>> {
(index < self.children.len()).then_some(self.children.remove(index))
}
pub fn children_len(&self) -> usize {
self.children.len()
}
pub fn size(&self) -> usize {
self.children
.iter()
.fold(self.children.len(), |len, node| -> usize {
len.saturating_add(node.size())
})
}
pub fn height(&self) -> usize {
self.children
.iter()
.map(|node| node.height())
.max()
.unwrap_or_default()
.saturating_add(1)
}
}
impl<T: Clone> Clone for Node<T> {
fn clone(&self) -> Self {
Self {
value: self.value.clone(),
children: self.children.clone(),
}
}
}
impl<T: PartialEq> PartialEq for Node<T> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.children == other.children
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_node_new() {
let root = Node::new(42);
assert_eq!(root.value(), &42);
assert_eq!(root.children_len(), 0);
}
#[test]
fn test_node_value_mut() {
let mut root = Node::new(42);
assert_eq!(root.value(), &42);
(*root.value_mut()) = 123;
assert_eq!(root.value(), &123);
}
#[test]
fn test_node_add_child() {
let mut root = node!(10);
root.add_child(node!(20));
root.add_child(node!(30));
assert_eq!(root.children_len(), 2);
}
#[test]
fn test_node_children_mut() {
let mut root = node!(10, node!(20), node!(30));
root.children_mut().swap(0, 1);
assert_eq!(root, node!(10, node!(30), node!(20)));
}
#[test]
fn test_node_remove_child() {
let mut root = node!(10, node!(20), node!(30));
let removed = root.remove_child(0);
assert_eq!(removed.unwrap().value(), &20);
assert_eq!(root.children_len(), 1);
}
#[test]
fn test_node_size() {
let root = node!(10, node!(20, node!(40)), node!(30, node!(50), node!(60)));
assert_eq!(root.size(), 5);
}
#[test]
fn test_node_height() {
let root = node!(10, node!(20, node!(40)), node!(30, node!(50), node!(60)));
assert_eq!(root.height(), 3);
}
#[test]
fn test_node_copy() {
let original = node!(10, node!(20), node!(30));
let mut copy = original.clone();
assert_eq!(copy, original);
copy.remove_child(0);
assert_ne!(copy, original);
}
}