1use std::fmt;
2use crate::{Node, iterator, change};
3use std::rc::Rc;
4use std::hash::Hash;
5use std::fmt::Debug;
6
7pub struct Tree<T> {
9 root: Node<T>,
11}
12
13impl<T> Tree<T>
14 where T: Eq + Hash {
15 pub fn new(string: &str, listener: Option<change::Listener<T>>) -> Tree<T> {
17 let mut root = Node::new_root(string);
18 if let Some(l) = listener {
19 root.give_listener(&Some(Rc::new(l)));
20 }
21
22 Tree {
23 root,
24 }
25 }
26
27 pub fn set(&mut self, start_idx: usize, end_idx: usize, info: T) {
30 self.root.set(start_idx, end_idx, Rc::new(info));
31 }
32
33 pub fn unset(&mut self, start_idx: usize, end_idx: usize, info: T) {
36 self.root.unset(start_idx, end_idx, Rc::new(info));
37 }
38
39 pub fn insert(&mut self, idx: usize, ch: char) {
41 self.root.insert(idx, ch);
42 }
43
44 pub fn insert_str(&mut self, idx: usize, string: &str) {
46 self.root.insert_str(idx, string);
47 }
48
49 pub fn push(&mut self, ch: char) {
51 self.root.push(ch);
52 }
53
54 pub fn push_str(&mut self, string: &str) {
56 self.root.push_str(string);
57 }
58
59 pub fn length(&self) -> usize {
61 self.root.length()
62 }
63
64 pub fn remove(&mut self, idx: usize, count: usize) {
66 self.root.remove(idx, count);
67 }
68
69 pub fn pop(&mut self) {
71 self.remove(self.length() - 1, 1);
72 }
73
74 pub fn clear(&mut self, keep_formats: bool) {
77 self.root.remove(0, self.length());
78
79 if !keep_formats {
80 self.root.clear_infos();
81 }
82 }
83
84 pub fn get_root(&self) -> &Node<T> {
86 &self.root
87 }
88
89 pub fn pre_order_iter(&self) -> iterator::PreOrder<T> {
91 self.root.pre_order_iter()
92 }
93
94 pub fn leaf_iter(&self) -> impl Iterator<Item=iterator::Item<T>> {
96 self.root.leaf_iter()
97 }
98}
99
100impl<T> fmt::Debug for Tree<T>
101 where T: Ord + Hash + Debug {
102 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103 write!(f, "{:?}", self.root)
104 }
105}