use std::cell::RefCell;
use std::rc::{Rc, Weak};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Node<T> {
parent: Option<Weak<Node<T>>>,
children: RefCell<Vec<Rc<Node<T>>>>,
pub value: T,
this: Weak<Self>,
}
impl<T> Node<T> {
pub fn root(value: T) -> Rc<Self> {
Rc::new_cyclic(|node| Self {
parent: None,
children: RefCell::new(Vec::new()),
value,
this: node.clone(),
})
}
pub fn create_child(&self, value: T) -> Rc<Node<T>> {
let child = Rc::new_cyclic(|child| Self {
parent: Some(self.this.clone()),
children: RefCell::new(Vec::new()),
value,
this: child.clone(),
});
self.children.borrow_mut().push(child.clone());
child
}
pub fn is_leaf(&self) -> bool {
self.children.borrow().is_empty()
}
pub fn parent(&self) -> Option<Rc<Node<T>>> {
self.parent.as_ref()?.upgrade()
}
pub fn children(&self) -> Vec<Rc<Node<T>>> {
self.children.borrow().iter().cloned().collect()
}
}