1pub use self::error::TreeError;
5use slab;
6use std::ops::{Index, IndexMut};
7use crate::tree::traversal::Traversable;
8use crate::types::{Children, DefaultIndexType, IndexType, NodeIndex, Tgf, Values, ValueType};
9
10#[cfg(test)]
11mod tests;
12
13pub mod error;
14
15pub trait GenericForest<V, Ix = DefaultIndexType>: Traversable<V, Ix>
17 where
18 V: ValueType,
19 Ix: IndexType,
20{
21 fn insert(&mut self, value: V) -> NodeIndex<Ix>;
23
24 fn insert_child(
29 &mut self,
30 parent: NodeIndex<Ix>,
31 value: V,
32 ) -> Result<NodeIndex<Ix>, TreeError<Ix>>;
33
34 fn insert_child_at(
40 &mut self,
41 parent: NodeIndex<Ix>,
42 pos: usize,
43 value: V,
44 ) -> Result<NodeIndex<Ix>, TreeError<Ix>>;
45
46 fn remove(&mut self, node: NodeIndex<Ix>) -> Result<V, TreeError<Ix>>;
50
51 fn remove_subtree(&mut self, node: NodeIndex<Ix>)
54 -> Result<Vec<(NodeIndex, V)>, TreeError<Ix>>;
55
56 fn set_as_child(
64 &mut self,
65 parent: NodeIndex<Ix>,
66 child: NodeIndex<Ix>,
67 ) -> Result<(), TreeError<Ix>>;
68
69 fn set_as_child_at(
78 &mut self,
79 parent: NodeIndex<Ix>,
80 child: NodeIndex<Ix>,
81 pos: usize,
82 ) -> Result<(), TreeError<Ix>>;
83
84 fn remove_as_child(&mut self, node: NodeIndex<Ix>) -> Result<(), TreeError<Ix>>;
88}
89
90#[derive(Debug, Clone)]
91struct Node<V>
92 where
93 V: ValueType,
94{
95 value: V,
96 child_count: usize,
97 context: NodeContext,
98}
99
100impl<V> Node<V>
101 where
102 V: ValueType,
103{
104 fn new(value: V) -> Self {
105 Node {
106 value,
107 child_count: 0,
108 context: NodeContext::new(),
109 }
110 }
111}
112
113#[derive(Copy, Clone, Debug)]
114struct NodeContext {
115 parent: Option<NodeIndex>,
116 first_child: Option<NodeIndex>,
117 last_child: Option<NodeIndex>,
118 prev_sibling: Option<NodeIndex>,
119 next_sibling: Option<NodeIndex>,
120}
121
122impl NodeContext {
123 fn new() -> Self {
124 NodeContext {
125 parent: None,
126 first_child: None,
127 last_child: None,
128 prev_sibling: None,
129 next_sibling: None,
130 }
131 }
132}
133
134struct ChildIterator<'slf, V>
135 where
136 V: ValueType,
137{
138 forest: &'slf Forest<V>,
139 current: Option<NodeIndex>,
140}
141
142impl<'slf, V> ChildIterator<'slf, V>
143 where
144 V: 'slf + ValueType,
145{
146 fn new(forest: &'slf Forest<V>, node: NodeIndex) -> Self {
147 ChildIterator {
148 forest,
149 current: forest
150 .arena
151 .get(node.index())
152 .and_then(|n| n.context.first_child),
153 }
154 }
155}
156
157impl<'slf, V> Iterator for ChildIterator<'slf, V>
158 where
159 V: 'slf + ValueType,
160{
161 type Item = NodeIndex;
162 fn next(&mut self) -> Option<NodeIndex> {
163 let ret = self.current;
164 match ret {
165 Some(n) => {
166 self.current = self.forest.arena[n.index()].context.next_sibling;
167 ret
168 }
169 None => None,
170 }
171 }
172}
173
174#[derive(Clone, Debug)]
236pub struct Forest<V>
237 where
238 V: ValueType,
239{
240 arena: slab::Slab<Node<V>>,
241 roots: Vec<NodeIndex>,
242}
243
244impl<V> Forest<V>
245 where
246 V: ValueType,
247{
248 pub fn new(size: usize) -> Self {
250 Forest {
251 arena: slab::Slab::with_capacity(size),
252 roots: Vec::new(),
253 }
254 }
255
256 pub fn first_child(&self, parent: NodeIndex) -> Option<NodeIndex> {
270 self.arena
271 .get(parent.index())
272 .and_then(|p| p.context.first_child)
273 }
274
275 pub fn last_child(&self, parent: NodeIndex) -> Option<NodeIndex> {
289 self.arena
290 .get(parent.index())
291 .and_then(|p| p.context.last_child)
292 }
293
294 pub fn prev_sibling(&self, node: NodeIndex) -> Option<NodeIndex> {
308 self.arena
309 .get(node.index())
310 .and_then(|n| n.context.prev_sibling)
311 }
312
313 pub fn next_sibling(&self, node: NodeIndex) -> Option<NodeIndex> {
327 self.arena
328 .get(node.index())
329 .and_then(|n| n.context.next_sibling)
330 }
331
332 pub fn roots(&self) -> &Vec<NodeIndex> {
347 &self.roots
348 }
349}
350
351impl<'slf, V> Children<'slf> for Forest<V>
352 where
353 V: 'slf + ValueType,
354{
355 fn children(&'slf self, node: NodeIndex) -> Box<dyn Iterator<Item=NodeIndex> + 'slf> {
356 Box::new(ChildIterator::new(self, node))
357 }
358}
359
360impl<V> Index<NodeIndex> for Forest<V>
361 where
362 V: ValueType,
363{
364 type Output = V;
365 fn index(&self, index: NodeIndex) -> &V {
366 &self.arena[index.index()].value
367 }
368}
369
370impl<V> IndexMut<NodeIndex> for Forest<V>
371 where
372 V: ValueType,
373{
374 fn index_mut(&mut self, index: NodeIndex) -> &mut V {
375 &mut self.arena[index.index()].value
376 }
377}
378
379impl<V> Traversable<V> for Forest<V>
380 where
381 V: ValueType,
382{
383 fn root(&self, node: NodeIndex) -> Option<NodeIndex> {
385 if let Some(_n) = self.arena.get(node.index()) {
386 let mut child = node;
387 while let Some(parent) = self.arena[child.index()].context.parent {
388 child = parent;
389 }
390 return Some(child);
391 }
392 None
393 }
394
395 fn value(&self, node: NodeIndex) -> Option<&V> {
397 self.arena.get(node.index()).map(|n| &n.value)
398 }
399
400 fn value_mut(&mut self, node: NodeIndex) -> Option<&mut V> {
402 self.arena.get_mut(node.index()).map(|n| &mut n.value)
403 }
404
405 fn parent(&self, node: NodeIndex) -> Option<NodeIndex> {
407 self.arena.get(node.index()).and_then(|n| n.context.parent)
408 }
409
410 fn child(&self, node: NodeIndex, pos: usize) -> Option<NodeIndex> {
412 ChildIterator::new(self, node).nth(pos)
413 }
414
415 fn child_count(&self, node: NodeIndex) -> usize {
417 self.arena.get(node.index()).map_or(0, |n| n.child_count)
418 }
419
420 fn node_count(&self) -> usize {
422 self.arena.len()
423 }
424}
425
426impl<'slf, V> Values<'slf, V> for Forest<V>
427 where
428 V: 'slf + ValueType,
429{
430 fn values(&'slf self) -> Box<dyn Iterator<Item=(NodeIndex, &'slf V)> + 'slf> {
433 Box::new(self.arena.iter().map(|(i, v)| (NodeIndex(i), &v.value)))
434 }
435}
436
437impl<V> GenericForest<V> for Forest<V>
438 where
439 V: ValueType,
440{
441 fn insert(&mut self, value: V) -> NodeIndex {
443 let node = NodeIndex(self.arena.insert(Node::new(value)));
444 self.roots.push(node);
445 node
446 }
447
448 fn insert_child(&mut self, parent: NodeIndex, value: V) -> Result<NodeIndex, TreeError> {
453 if !self.arena.contains(parent.index()) {
454 return Err(TreeError::invalid_node_index("insert_child()", parent));
455 }
456 let child = NodeIndex(self.arena.insert(Node::new(value)));
457
458 match self.arena[parent.index()].context.last_child {
459 Some(last) => {
460 self.arena[last.index()].context.next_sibling = Some(child);
461 self.arena[parent.index()].context.last_child = Some(child);
462 self.arena[child.index()].context.prev_sibling = Some(last);
463 }
464 None => {
465 self.arena[parent.index()].context.first_child = Some(child);
466 self.arena[parent.index()].context.last_child = Some(child);
467 }
468 }
469 self.arena[child.index()].context.parent = Some(parent);
470 self.arena[parent.index()].child_count += 1;
471 Ok(child)
472 }
473
474 fn insert_child_at(
480 &mut self,
481 parent: NodeIndex,
482 pos: usize,
483 value: V,
484 ) -> Result<NodeIndex, TreeError> {
485 if !self.arena.contains(parent.index()) {
486 return Err(TreeError::invalid_node_index("insert_child_at()", parent));
487 }
488 let child = NodeIndex(self.arena.insert(Node::new(value)));
489
490 let mut prev = None;
491 let mut next = self.arena[parent.index()].context.first_child;
492 let mut i = 0;
493
494 while i < pos {
495 match next {
496 Some(n) => {
497 prev = next;
498 next = self.arena[n.index()].context.next_sibling;
499 i += 1;
500 }
501 None => {
502 break;
503 }
504 }
505 }
506 match (prev, next) {
507 (None, Some(n)) => {
508 self.arena[n.index()].context.prev_sibling = Some(child);
509 self.arena[parent.index()].context.first_child = Some(child);
510 }
511 (Some(p), Some(n)) => {
512 self.arena[n.index()].context.prev_sibling = Some(child);
513 self.arena[p.index()].context.next_sibling = Some(child);
514 }
515 (Some(p), None) => {
516 self.arena[p.index()].context.next_sibling = Some(child);
517 self.arena[parent.index()].context.last_child = Some(child);
518 }
519 (None, None) => {
520 self.arena[parent.index()].context.first_child = Some(child);
521 self.arena[parent.index()].context.last_child = Some(child);
522 }
523 }
524 self.arena[child.index()].context.parent = Some(parent);
525 self.arena[child.index()].context.prev_sibling = prev;
526 self.arena[child.index()].context.next_sibling = next;
527 self.arena[parent.index()].child_count += 1;
528 Ok(child)
529 }
530
531 fn remove(&mut self, node: NodeIndex) -> Result<V, TreeError> {
535 if !self.arena.contains(node.index()) {
536 return Err(TreeError::invalid_node_index("remove()", node));
537 }
538
539 let context = self.arena[node.index()].context;
540 match context.parent {
541 Some(parent) => {
542 match (
543 context.first_child,
544 context.last_child,
545 context.prev_sibling,
546 context.next_sibling,
547 ) {
548 (Some(first), Some(last), Some(prev), Some(next)) => {
549 self.arena[prev.index()].context.next_sibling = Some(first);
550 self.arena[next.index()].context.prev_sibling = Some(last);
551 self.arena[first.index()].context.prev_sibling = Some(prev);
552 self.arena[last.index()].context.next_sibling = Some(next);
553 }
554 (Some(first), Some(last), Some(prev), None) => {
555 self.arena[parent.index()].context.last_child = Some(last);
556 self.arena[first.index()].context.prev_sibling = Some(prev);
557 self.arena[prev.index()].context.next_sibling = Some(first);
558 }
559 (Some(first), Some(last), None, Some(next)) => {
560 self.arena[parent.index()].context.first_child = Some(first);
561 self.arena[last.index()].context.next_sibling = Some(next);
562 self.arena[next.index()].context.prev_sibling = Some(last);
563 }
564 (Some(first), Some(last), None, None) => {
565 self.arena[parent.index()].context.first_child = Some(first);
566 self.arena[parent.index()].context.last_child = Some(last);
567 }
568 (None, None, Some(prev), Some(next)) => {
569 self.arena[prev.index()].context.next_sibling = Some(next);
570 self.arena[next.index()].context.prev_sibling = Some(prev);
571 }
572
573 (None, None, Some(prev), None) => {
574 self.arena[parent.index()].context.last_child = Some(prev);
575 self.arena[prev.index()].context.next_sibling = None;
576 }
577
578 (None, None, None, Some(next)) => {
579 self.arena[parent.index()].context.first_child = Some(next);
580 self.arena[next.index()].context.prev_sibling = None;
581 }
582
583 (None, None, None, None) => {
584 self.arena[parent.index()].context.first_child = None;
585 self.arena[parent.index()].context.last_child = None;
586 }
587 _ => panic!("remove(): first and last child indices are incorrect"),
588 }
589 let mut child = self.arena[node.index()].context.first_child;
590 while let Some(c) = child {
591 child = self.arena[c.index()].context.next_sibling;
592 self.arena[c.index()].context.parent = Some(parent);
593 }
594 self.arena[parent.index()].child_count -= 1;
595 self.arena[parent.index()].child_count += self.arena[node.index()].child_count;
596 }
597 None => {
598 self.roots.retain(|&r| r != node);
599 let mut child = self.arena[node.index()].context.first_child;
600 while let Some(c) = child {
601 child = self.arena[c.index()].context.next_sibling;
602 self.arena[c.index()].context.parent = None;
603 self.arena[c.index()].context.prev_sibling = None;
604 self.arena[c.index()].context.next_sibling = None;
605 self.roots.push(c);
606 }
607 }
608 }
609 Ok(self.arena.remove(node.index()).value)
610 }
611
612 fn remove_subtree(&mut self, node: NodeIndex) -> Result<Vec<(NodeIndex, V)>, TreeError> {
615 if self.remove_as_child(node).is_err() {
616 return Err(TreeError::invalid_node_index("remove_subtree()", node));
617 }
618
619 let mut stack = Vec::with_capacity(self.arena[node.index()].child_count + 1);
620 let mut ret = Vec::with_capacity(stack.capacity());
621 stack.push(node);
622 while let Some(parent) = stack.pop() {
623 let mut child = self.arena[parent.index()].context.last_child;
624 while let Some(c) = child {
625 stack.push(c);
626 child = self.arena[c.index()].context.prev_sibling;
627 }
628 ret.push((parent, self.arena.remove(parent.index()).value));
629 }
630 self.roots.retain(|&r| r != node);
631 Ok(ret)
632 }
633
634 fn set_as_child(&mut self, parent: NodeIndex, child: NodeIndex) -> Result<(), TreeError> {
642 if !self.arena.contains(parent.index()) {
643 return Err(TreeError::invalid_node_index("set_as_child()", parent));
644 }
645 if !self.arena.contains(child.index()) {
646 return Err(TreeError::invalid_node_index("set_as_child()", child));
647 }
648 if self.arena[child.index()].context.parent.is_some() {
649 return Err(TreeError::expected_root_node("set_as_child()", child));
650 }
651 if self.root(parent) == Some(child) {
652 return Err(TreeError::expected_non_ancestor_node(
653 "set_as_child()",
654 parent,
655 child,
656 ));
657 }
658
659 match self.arena[parent.index()].context.last_child {
660 Some(last) => {
661 self.arena[last.index()].context.next_sibling = Some(child);
662 self.arena[child.index()].context.prev_sibling = Some(last);
663 self.arena[parent.index()].context.last_child = Some(child);
664 }
665 None => {
666 self.arena[parent.index()].context.first_child = Some(child);
667 self.arena[parent.index()].context.last_child = Some(child);
668 }
669 }
670 self.arena[child.index()].context.parent = Some(parent);
671 self.arena[parent.index()].child_count += 1;
672 self.roots.retain(|&r| r != child);
673 Ok(())
674 }
675
676 fn set_as_child_at(
685 &mut self,
686 parent: NodeIndex,
687 child: NodeIndex,
688 pos: usize,
689 ) -> Result<(), TreeError> {
690 if !self.arena.contains(parent.index()) {
691 return Err(TreeError::invalid_node_index("set_as_child_at()", parent));
692 }
693 if !self.arena.contains(child.index()) {
694 return Err(TreeError::invalid_node_index("set_as_child_at()", child));
695 }
696 if self.arena[child.index()].context.parent.is_some() {
697 return Err(TreeError::expected_root_node("set_as_child_at()", child));
698 }
699 if self.root(parent) == Some(child) {
700 return Err(TreeError::expected_non_ancestor_node(
701 "set_as_child_at()",
702 parent,
703 child,
704 ));
705 }
706
707 let mut prev = None;
708 let mut next = self.arena[parent.index()].context.first_child;
709 let mut i = 0;
710
711 while i < pos {
712 match next {
713 Some(n) => {
714 prev = next;
715 next = self.arena[n.index()].context.next_sibling;
716 i += 1;
717 }
718 None => {
719 break;
720 }
721 }
722 }
723 match (prev, next) {
724 (None, Some(n)) => {
725 self.arena[n.index()].context.prev_sibling = Some(child);
726 self.arena[parent.index()].context.first_child = Some(child);
727 }
728 (Some(p), Some(n)) => {
729 self.arena[n.index()].context.prev_sibling = Some(child);
730 self.arena[p.index()].context.next_sibling = Some(child);
731 }
732 (Some(p), None) => {
733 self.arena[p.index()].context.next_sibling = Some(child);
734 self.arena[parent.index()].context.last_child = Some(child);
735 }
736 (None, None) => {
737 self.arena[parent.index()].context.first_child = Some(child);
738 self.arena[parent.index()].context.last_child = Some(child);
739 }
740 }
741 self.arena[child.index()].context.parent = Some(parent);
742 self.arena[child.index()].context.prev_sibling = prev;
743 self.arena[child.index()].context.next_sibling = next;
744 self.arena[parent.index()].child_count += 1;
745 self.roots.retain(|&r| r != child);
746 Ok(())
747 }
748
749 fn remove_as_child(&mut self, node: NodeIndex) -> Result<(), TreeError> {
753 if !self.arena.contains(node.index()) {
754 return Err(TreeError::invalid_node_index("remove_as_child()", node));
755 }
756 let context = self.arena[node.index()].context;
757
758 if let Some(parent) = context.parent {
759 match (context.prev_sibling, context.next_sibling) {
760 (Some(prev), Some(next)) => {
761 self.arena[prev.index()].context.next_sibling = Some(next);
762 self.arena[next.index()].context.prev_sibling = Some(prev);
763 }
764 (Some(prev), None) => {
765 self.arena[prev.index()].context.next_sibling = None;
766 self.arena[parent.index()].context.last_child = Some(prev);
767 }
768 (None, Some(next)) => {
769 self.arena[next.index()].context.prev_sibling = None;
770 self.arena[parent.index()].context.first_child = Some(next);
771 }
772 (None, None) => {
773 self.arena[parent.index()].context.first_child = None;
774 self.arena[parent.index()].context.last_child = None;
775 }
776 }
777 self.arena[parent.index()].child_count -= 1;
778 self.roots.push(node);
779 }
780 self.arena[node.index()].context = NodeContext {
781 parent: None,
782 first_child: context.first_child,
783 last_child: context.last_child,
784 prev_sibling: None,
785 next_sibling: None,
786 };
787 Ok(())
788 }
789}
790
791impl<V> Tgf for Forest<V>
792 where
793 V: ValueType,
794{
795 fn to_tgf(&self) -> String {
796 let mut nodes = String::from("");
797 let mut edges = String::from("");
798 let iter = self.arena.iter();
799 for (index, node) in iter {
800 nodes.push_str(format!("{}", index).as_str());
801 nodes.push_str(" [K = ");
802 nodes.push_str(format!("{}", index).as_str());
803 nodes.push_str(", V = ");
804 nodes.push_str(format!("{:?}", node.value).as_str());
805 nodes.push_str("]\n");
806
807 for child in self.children(NodeIndex(index)).enumerate() {
808 edges.push_str(format!("{}", index).as_str());
809 edges.push_str(" ");
810 edges.push_str(format!("{}", child.1.index()).as_str());
811 edges.push_str(" ");
812 edges.push_str(format!("{}", child.0).as_str());
813 edges.push_str("\n");
814 }
815 }
816 nodes.push_str("#\n");
817 nodes.push_str(edges.as_str());
818 nodes
819 }
820}