pub trait TreeDisplay {
fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result;
}
const INDENT: usize = 2;
#[derive(derive_more::Deref, Clone, Copy)]
pub struct TreeState {
#[deref]
pub depth: usize,
pub debug: bool,
}
impl TreeState {
pub fn new_display() -> Self {
Self {
depth: 0,
debug: false,
}
}
pub fn new_debug(depth: usize) -> Self {
Self { depth, debug: true }
}
pub fn indent(&mut self) {
self.depth += INDENT
}
pub fn indented(&self) -> Self {
Self {
depth: self.depth + INDENT,
debug: self.debug,
}
}
}
pub struct FormatTree<'a, T: TreeDisplay>(pub &'a T);
impl<T: TreeDisplay> std::fmt::Display for FormatTree<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.tree_print(
f,
TreeState {
depth: 2,
debug: false,
},
)
}
}
impl<T: TreeDisplay> std::fmt::Debug for FormatTree<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.tree_print(
f,
TreeState {
depth: 2,
debug: true,
},
)
}
}