use std::fmt;
use crate::{Node, iterator, change};
use std::rc::Rc;
use std::hash::Hash;
use std::fmt::Debug;
pub struct Tree<T> {
root: Node<T>,
}
impl<T> Tree<T>
where T: Eq + Hash {
pub fn new(string: &str, listener: Option<change::Listener<T>>) -> Tree<T> {
let mut root = Node::new_root(string);
if let Some(l) = listener {
root.give_listener(&Some(Rc::new(l)));
}
Tree {
root,
}
}
pub fn set(&mut self, start_idx: usize, end_idx: usize, info: T) {
self.root.set(start_idx, end_idx, Rc::new(info));
}
pub fn unset(&mut self, start_idx: usize, end_idx: usize, info: T) {
self.root.unset(start_idx, end_idx, Rc::new(info));
}
pub fn insert(&mut self, idx: usize, ch: char) {
self.root.insert(idx, ch);
}
pub fn insert_str(&mut self, idx: usize, string: &str) {
self.root.insert_str(idx, string);
}
pub fn push(&mut self, ch: char) {
self.root.push(ch);
}
pub fn push_str(&mut self, string: &str) {
self.root.push_str(string);
}
pub fn length(&self) -> usize {
self.root.length()
}
pub fn remove(&mut self, idx: usize, count: usize) {
self.root.remove(idx, count);
}
pub fn pop(&mut self) {
self.remove(self.length() - 1, 1);
}
pub fn clear(&mut self, keep_formats: bool) {
self.root.remove(0, self.length());
if !keep_formats {
self.root.clear_infos();
}
}
pub fn get_root(&self) -> &Node<T> {
&self.root
}
pub fn pre_order_iter(&self) -> iterator::PreOrder<T> {
self.root.pre_order_iter()
}
pub fn leaf_iter(&self) -> impl Iterator<Item=iterator::Item<T>> {
self.root.leaf_iter()
}
}
impl<T> fmt::Debug for Tree<T>
where T: Ord + Hash + Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.root)
}
}