1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use crate::vec_tree::RoseVecTree;
use std::{fmt::Display, iter::repeat};

#[derive(Clone, Copy, Debug)]
pub struct Indenter {
    /// Indenter Docs
    /// ╠═Controls how to render tree-format data
    /// ╠═Character varieties
    /// ║ ╠═left_bar <║>
    /// ║ ╠═inward_branch <╠>
    /// ║ ╠═horizontal_bar <═>
    /// ║ ╚═last_entry <╚>
    /// ╠═Indenting parameters
    /// ║ ╠═current_level
    /// ║ ║ ╚═Tracks which indent level we're on. This sentence is on level 3!
    /// ║ ╚═level_width
    /// ║   ╚═States how wide each level's decorations should be.
    /// ╚═This takes TreeFormat types and renders them as pretty-printed trees. It
    /// does not currently cope with wraparound (oops).
    current_level: usize,
    level_width: usize,
    vertical_bar: char,
    inward_branch: char,
    horizontal_bar: char,
    last_entry: char,
}

/// An object used by the TreeFormat to control and track formatting settings.
impl Indenter {
    pub fn next(&self) -> Indenter {
        Indenter {
            current_level: self.current_level + 1,
            ..*self
        }
    }

    /// How long the header of a line should be for this indenter.
    pub fn header_len(&self) -> usize {
        self.current_level * self.level_width
    }

    /// Generate the text of the header for the line.
    pub fn line_header(&self, arms_to_continue: &Vec<bool>) -> String {
        let mut accum = String::with_capacity(self.header_len());
        let mut arm_iter = arms_to_continue.iter();
        let is_last_line = if let Some(arm) = arm_iter.next_back() {
            !arm
        } else {
            return String::with_capacity(0);
        };

        for arm in arm_iter {
            // Add bridging bar, if needed.
            if *arm {
                accum.push(self.vertical_bar)
            } else {
                accum.push(' ')
            };
            // Adding the horizontal spacing.
            accum.extend(repeat(' ').take(self.level_width - 1));
        }

        let bar = if is_last_line {
            self.last_entry
        } else {
            self.inward_branch
        };
        accum.push(bar);
        accum.extend(repeat(self.horizontal_bar).take(self.level_width - 1));
        accum
    }

    /// Pads a string with the header, toggling branches based on the arms outside
    /// of the current layer.
    pub fn pad_string(&self, continue_arms: &Vec<bool>, text: &String) -> String {
        format!("{}{}", self.line_header(continue_arms), text)
    }

    /// Pads every string in a RoseVecTree, producing a new, padded RoseVecTree.
    pub fn pad_tree(&self, tree: &RoseVecTree<String>) -> RoseVecTree<String> {
        fn rec_pad(
            indenter: &Indenter,
            tree: &RoseVecTree<String>,
            continue_arms: &mut Vec<bool>,
        ) -> RoseVecTree<String> {
            match tree {
                //RoseVecTree::Empty => RoseVecTree::Empty,
                RoseVecTree::Leaf(val) => {
                    RoseVecTree::Leaf(indenter.pad_string(continue_arms, val))
                }
                RoseVecTree::Branch(head, children) => {
                    let new_head = indenter.pad_string(continue_arms, head);

                    let mut child_iter = children.iter();
                    let last_child = if let Some(child) = child_iter.next_back() {
                        child
                    } else {
                        return RoseVecTree::Leaf(new_head);
                    };
                    let child_indenter = indenter.next();
                    let mut new_children = Vec::with_capacity(children.len());

                    continue_arms.push(true);
                    for child in child_iter {
                        new_children.push(rec_pad(&child_indenter, child, continue_arms));
                    }
                    continue_arms.pop();

                    continue_arms.push(false);
                    new_children.push(rec_pad(&child_indenter, last_child, continue_arms));
                    continue_arms.pop();
                    RoseVecTree::Branch(new_head, new_children)
                }
            }
        }
        rec_pad(self, tree, &mut Vec::with_capacity(self.current_level))
    }
}

/// Very convenient, I'm not copy-pasting the fancy characters every single
/// time.
impl Default for Indenter {
    fn default() -> Self {
        Self {
            current_level: 0,
            level_width: 2,
            horizontal_bar: '═',
            inward_branch: '╠',
            last_entry: '╚',
            vertical_bar: '║',
        }
    }
}

/// A trait which allows implementers to specify how they should be printed as
/// a tree.
pub trait TreeFormat {
    /// The only thing you need to define is the conversion from your type to a
    /// RoseVecTree.
    fn treeify(&self) -> RoseVecTree<String>;

    /// Indent adds the decorations to the strings of the tree with the default
    /// formatter.
    fn indent(&self) -> RoseVecTree<String> {
        Indenter::default().pad_tree(&self.treeify())
    }

    /// Actually converts the tree into a single string for printing.
    fn fmt_tree(&self) -> String {
        self.indent()
            .preorder_iter()
            .fold(String::new(), |accum, line| accum + "\n" + line)
    }
}

/// If you're a RoseVecTree, you get TreeFormat for free so long as T can be
/// printed. If printing T involves printing newlines, don't. It'll get weird.
impl<T: Display> TreeFormat for RoseVecTree<T> {
    fn treeify(&self) -> RoseVecTree<String> {
        self.map(&|val| val.to_string())
    }
}

impl Display for dyn TreeFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.fmt_tree())
    }
}

#[cfg(test)]
mod test {
    use super::Indenter;
    use crate::{format::TreeFormat, vec_tree::RoseVecTree};

    #[test]
    fn indent_levels() {
        let indenter = Indenter::default();
        assert_eq!(indenter.line_header(&vec![]), "", "{:#?}", indenter);
        assert_eq!(indenter.line_header(&vec![]), "", "{:#?}", indenter);

        let indenter = indenter.next();
        assert_eq!(indenter.line_header(&vec![true]), "╠═", "{:#?}", indenter);
        assert_eq!(indenter.line_header(&vec![false]), "╚═", "{:#?}", indenter);

        let indenter = indenter.next();
        assert_eq!(
            indenter.line_header(&vec![true, true]),
            "║ ╠═",
            "{:#?}",
            indenter
        );
        assert_eq!(
            indenter.line_header(&vec![true, false]),
            "║ ╚═",
            "{:#?}",
            indenter
        );
    }

    #[test]
    fn skip_level() {
        let _indenter = Indenter::default();
        let doc_tree = RoseVecTree::Branch(
            "Level 0",
            vec![
                RoseVecTree::Branch(
                    "Level 1",
                    vec![RoseVecTree::Branch(
                        "Level 2",
                        vec![RoseVecTree::Leaf("Level 3")],
                    )],
                ),
                RoseVecTree::Leaf("Bottom"),
            ],
        );
        assert_eq!(
            r#"
Level 0
╠═Level 1
║ ╚═Level 2
║   ╚═Level 3
╚═Bottom"#,
            doc_tree.fmt_tree()
        );
    }

    #[test]
    fn print_the_docs() {
        let doc_tree = RoseVecTree::Branch(
      "Indenter Docs",
      vec! [
        RoseVecTree::Leaf("Controls how to render tree-format data"),
        RoseVecTree::Branch(
          "Character varieties",
          vec! [
            RoseVecTree::Leaf("left_bar <║>"),
            RoseVecTree::Leaf("inward_branch <╠>"),
            RoseVecTree::Leaf("horizontal_bar <═>"),
            RoseVecTree::Leaf("last_entry <╚>")]),
        RoseVecTree::Branch(
          "Indenting parameters",
          vec! [
            RoseVecTree::Branch(
              "current_level",
              vec! [
                RoseVecTree::Leaf("Tracks which indent level we're on. This sentence is on level 3!")]),
            RoseVecTree::Branch(
              "level_width",
              vec! [
                RoseVecTree::Leaf("States how wide each level's decorations should be.")]),
        ]),
      RoseVecTree::Leaf("This takes TreeFormat types and renders them as pretty-printed trees. It does not currently cope with wraparound (oops).")]);

        println!("{}", doc_tree.fmt_tree())
    }
}