radiate_gp/collections/trees/
format.rs1use super::{Tree, TreeNode};
2use crate::Node;
3use std::fmt::Debug;
4
5pub trait Format {
6 fn format(&self) -> String;
7}
8
9impl<T: Debug> Format for TreeNode<T> {
10 fn format(&self) -> String {
11 fn pretty_print_lines<T: Debug>(
12 node: &TreeNode<T>,
13 prefix: &str,
14 is_last: bool,
15 result: &mut String,
16 ) {
17 let connector = if is_last { "└── " } else { "├── " };
18 result.push_str(&format!("{}{}{:?}\n", prefix, connector, node.value()));
19
20 if let Some(children) = &node.children() {
21 let len = children.len();
22 for (i, child) in children.iter().enumerate() {
23 let is_last_child = i == len - 1;
24 let new_prefix = if is_last {
25 format!("{} ", prefix)
26 } else {
27 format!("{}│ ", prefix)
28 };
29
30 pretty_print_lines(child, &new_prefix, is_last_child, result);
31 }
32 }
33 }
34 let mut result = String::new();
35 if self.children().is_some() {
36 result += "\n";
37 }
38
39 pretty_print_lines(self, "", true, &mut result);
40
41 result
42 }
43}
44
45impl<T: Debug> Format for Tree<T> {
46 fn format(&self) -> String {
47 self.root()
48 .map(|node| node.format())
49 .unwrap_or_else(|| "Empty Tree".to_string())
50 }
51}
52
53impl<T: Debug> Format for Vec<Tree<T>> {
54 fn format(&self) -> String {
55 let mut result = String::new();
56 for (i, tree) in self.iter().enumerate() {
57 result += &format!("Tree {}:\n", i);
58 result += &tree.format();
59 }
60 result
61 }
62}