iter_tree/tree/
into_tree.rs1use super::Tree;
2use crate::{Nesting, NestingFunction};
3
4pub trait IntoTreeExt<Token> {
5 fn into_tree<F>(self, fun: F) -> Tree<Token>
6 where
7 F: NestingFunction<Token>;
8}
9
10impl<Iterable, Token> IntoTreeExt<Token> for Iterable
11where
12 Iterable: IntoIterator<Item = Token>,
13{
14 fn into_tree<F>(self, mut fun: F) -> Tree<Token>
15 where
16 F: NestingFunction<Token>,
17 {
18 let mut container = Vec::new();
19 let mut parents = Vec::new();
20
21 for token in self {
22 match fun.direction(&token) {
23 Nesting::Increase => {
24 let mut parent = Vec::new();
25 core::mem::swap(&mut parent, &mut container);
26 parents.push(parent);
27 container.push(Tree::Leaf(token));
28 }
29
30 Nesting::Maintain => container.push(Tree::Leaf(token)),
31 Nesting::Decrease => {
32 let mut parent = parents.pop().unwrap_or(Vec::new());
33 container.push(Tree::Leaf(token));
34 parent.push(Tree::Node(container));
35 container = parent;
36 }
37 }
38 }
39
40 while let Some(mut parent) = parents.pop() {
41 parent.push(Tree::Node(container));
42 container = parent;
43 }
44
45 Tree::Node(container)
46 }
47}