use crate::style::Style;
use std::borrow::Cow;
use std::io;
pub trait TreeItem: Clone {
type Child: TreeItem;
fn write_self<W: io::Write>(&self, f: &mut W, style: &Style) -> io::Result<()>;
fn children(&self) -> Cow<[Self::Child]>;
}
#[derive(Clone, Debug)]
pub struct StringItem {
pub text: String,
pub children: Vec<StringItem>,
}
impl TreeItem for StringItem {
type Child = Self;
fn write_self<W: io::Write>(&self, f: &mut W, style: &Style) -> io::Result<()> {
write!(f, "{}", style.paint(&self.text))
}
fn children(&self) -> Cow<[Self::Child]> {
Cow::from(&self.children[..])
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
use std::str::from_utf8;
use crate::output::write_tree_with;
use crate::print_config::PrintConfig;
#[test]
fn small_item_output() {
let deps = StringItem {
text: "petgraph".to_string(),
children: vec![
StringItem {
text: "quickcheck".to_string(),
children: vec![
StringItem {
text: "libc".to_string(),
children: vec![],
},
StringItem {
text: "rand".to_string(),
children: vec![StringItem {
text: "libc".to_string(),
children: vec![],
}],
},
],
},
StringItem {
text: "fixedbitset".to_string(),
children: vec![],
},
],
};
let config = PrintConfig {
indent: 4,
leaf: Style::default(),
branch: Style::default(),
..PrintConfig::default()
};
let mut cursor: Cursor<Vec<u8>> = Cursor::new(Vec::new());
write_tree_with(&deps, &mut cursor, &config).unwrap();
let data = cursor.into_inner();
let expected = "\
petgraph\n\
├── quickcheck\n\
│ ├── libc\n\
│ └── rand\n\
│ └── libc\n\
└── fixedbitset\n\
";
assert_eq!(from_utf8(&data).unwrap(), expected);
}
}