Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![allow(dead_code)]
- #![allow(unused_variables)]
- pub struct Node {
- label: String,
- nodes: Vec<Node>,
- }
- impl Node {
- pub fn new(label: impl Into<String>, nodes: Vec<Node>) -> Node {
- Node {
- label: label.into(),
- nodes,
- }
- }
- }
- pub struct Opts {
- pub unicode: bool
- }
- impl Opts {
- pub fn new() -> Opts { Default::default() }
- pub fn unicode(mut self, value: bool) -> Opts {
- self.unicode = value;
- self
- }
- }
- impl Default for Opts {
- fn default() -> Self { Opts { unicode: true } }
- }
- pub fn archy(node: &Node, prefix: &str, opts: &Opts) -> String {
- let get_char = |input| -> &str {
- match input {
- "│" => if opts.unicode { "│" } else { "|" },
- "└" => if opts.unicode { "└" } else { "`" },
- "├" => if opts.unicode { "├" } else { "+" },
- "─" => if opts.unicode { "─" } else { "-" },
- "┬" => if opts.unicode { "┬" } else { "-" },
- _ => ""
- }
- };
- let lines: Vec<&str> = node.label.lines().collect();
- let node_len = node.nodes.len();
- let suf = if node_len > 0 { get_char("│") } else { " " };
- let splitter = format!("\n{}{} ", prefix, suf);
- let child = node.nodes.iter().enumerate().map(|(ix, node)| {
- let last = ix == (node_len - 1);
- let more = node.nodes.len() > 0;
- let prefix_ = format!("{}{} ", prefix, if last { " " } else { get_char("│") });
- let next_string = archy(&node, prefix_.as_str(), opts);
- let target_num = prefix.char_indices().count() + 2;
- let next_output = next_string.char_indices()
- .skip(target_num)
- .map(|(i, char)| char.to_string())
- .collect::<Vec<String>>()
- .join("");
- vec![prefix,
- if last { get_char("└") } else { get_char("├") },
- get_char("─"),
- if more { get_char("┬") } else { get_char("─") },
- " ",
- next_output.as_str()
- ].join("")
- }).collect::<Vec<String>>();
- format!("{}{}\n{}", prefix, lines.join(splitter.as_str()), child.join(""))
- }
- fn main() {
- let node = Node::new("One", vec![
- Node::new("Two\nwith\nNew\nLine", vec![]),
- Node::new("Three", vec![
- Node::new("Four", vec![
- Node::new("Four nested", vec![]),
- Node::new("Five nested", vec![]),
- Node::new("Six nested", vec![]),
- Node::new("Seven nested", vec![]),
- ]),
- Node::new("Five", vec![]),
- Node::new("Six", vec![]),
- Node::new("Seven", vec![]),
- ])
- ]);
- let opts = Opts::new();
- let output = archy(&node, "", &opts);
- println!("{}", output);
- }
Add Comment
Please, Sign In to add comment