Guest User

Untitled

a guest
Jul 21st, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. #![allow(dead_code)]
  2. #![allow(unused_variables)]
  3.  
  4. pub struct Node {
  5. label: String,
  6. nodes: Vec<Node>,
  7. }
  8.  
  9. impl Node {
  10. pub fn new(label: impl Into<String>, nodes: Vec<Node>) -> Node {
  11. Node {
  12. label: label.into(),
  13. nodes,
  14. }
  15. }
  16. }
  17.  
  18. pub struct Opts {
  19. pub unicode: bool
  20. }
  21.  
  22. impl Opts {
  23. pub fn new() -> Opts { Default::default() }
  24. pub fn unicode(mut self, value: bool) -> Opts {
  25. self.unicode = value;
  26. self
  27. }
  28. }
  29.  
  30. impl Default for Opts {
  31. fn default() -> Self { Opts { unicode: true } }
  32. }
  33.  
  34. pub fn archy(node: &Node, prefix: &str, opts: &Opts) -> String {
  35. let get_char = |input| -> &str {
  36. match input {
  37. "│" => if opts.unicode { "│" } else { "|" },
  38. "└" => if opts.unicode { "└" } else { "`" },
  39. "├" => if opts.unicode { "├" } else { "+" },
  40. "─" => if opts.unicode { "─" } else { "-" },
  41. "┬" => if opts.unicode { "┬" } else { "-" },
  42. _ => ""
  43. }
  44. };
  45. let lines: Vec<&str> = node.label.lines().collect();
  46. let node_len = node.nodes.len();
  47. let suf = if node_len > 0 { get_char("│") } else { " " };
  48. let splitter = format!("\n{}{} ", prefix, suf);
  49.  
  50. let child = node.nodes.iter().enumerate().map(|(ix, node)| {
  51. let last = ix == (node_len - 1);
  52. let more = node.nodes.len() > 0;
  53. let prefix_ = format!("{}{} ", prefix, if last { " " } else { get_char("│") });
  54. let next_string = archy(&node, prefix_.as_str(), opts);
  55. let target_num = prefix.char_indices().count() + 2;
  56.  
  57. let next_output = next_string.char_indices()
  58. .skip(target_num)
  59. .map(|(i, char)| char.to_string())
  60. .collect::<Vec<String>>()
  61. .join("");
  62.  
  63. vec![prefix,
  64. if last { get_char("└") } else { get_char("├") },
  65. get_char("─"),
  66. if more { get_char("┬") } else { get_char("─") },
  67. " ",
  68. next_output.as_str()
  69. ].join("")
  70. }).collect::<Vec<String>>();
  71.  
  72. format!("{}{}\n{}", prefix, lines.join(splitter.as_str()), child.join(""))
  73. }
  74.  
  75. fn main() {
  76. let node = Node::new("One", vec![
  77. Node::new("Two\nwith\nNew\nLine", vec![]),
  78. Node::new("Three", vec![
  79. Node::new("Four", vec![
  80. Node::new("Four nested", vec![]),
  81. Node::new("Five nested", vec![]),
  82. Node::new("Six nested", vec![]),
  83. Node::new("Seven nested", vec![]),
  84. ]),
  85. Node::new("Five", vec![]),
  86. Node::new("Six", vec![]),
  87. Node::new("Seven", vec![]),
  88. ])
  89. ]);
  90.  
  91. let opts = Opts::new();
  92. let output = archy(&node, "", &opts);
  93.  
  94. println!("{}", output);
  95. }
Add Comment
Please, Sign In to add comment