|
| 1 | +use std::fmt::Display; |
| 2 | + |
| 3 | +/// Indentation token |
| 4 | +#[derive(Debug)] |
| 5 | +struct Token { |
| 6 | + /// Is followed by a brother |
| 7 | + siblings: bool, |
| 8 | + /// Is intermediate while printing children |
| 9 | + children: bool, |
| 10 | +} |
| 11 | + |
| 12 | +impl ToString for Token { |
| 13 | + fn to_string(&self) -> String { |
| 14 | + let Token { siblings, children } = self; |
| 15 | + |
| 16 | + match (siblings, children) { |
| 17 | + (true, true) => "│ ", |
| 18 | + (true, false) => "├── ", |
| 19 | + (false, true) => " ", |
| 20 | + (false, false) => "└── ", |
| 21 | + } |
| 22 | + .to_string() |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl Token { |
| 27 | + /// Create a new indentation token |
| 28 | + fn new(siblings: bool) -> Self { |
| 29 | + Token { |
| 30 | + siblings, |
| 31 | + children: false, |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + /// Set children flag before starting displaying children |
| 36 | + fn set_children(&mut self) { |
| 37 | + self.children = true; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/// Manages the state during the display operation |
| 42 | +#[derive(Debug)] |
| 43 | +pub struct Indentation { |
| 44 | + tokens: Vec<Token>, |
| 45 | + ignore_root: bool, |
| 46 | +} |
| 47 | + |
| 48 | +impl Display for Indentation { |
| 49 | + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 50 | + let first: usize = if self.ignore_root { 1 } else { 0 }; |
| 51 | + |
| 52 | + for token in &self.tokens[first..] { |
| 53 | + write!(f, "{}", token.to_string())?; |
| 54 | + } |
| 55 | + |
| 56 | + Ok(()) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl Indentation { |
| 61 | + /// Creates a new indentation handler |
| 62 | + pub fn new(ignore_root: bool) -> Self { |
| 63 | + Indentation { |
| 64 | + tokens: Vec::new(), |
| 65 | + ignore_root, |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + /// Adds a new layer of indentation |
| 70 | + pub fn indent(&mut self, siblings: bool) -> &mut Self { |
| 71 | + // Setup children mode for previous tokens |
| 72 | + let len = self.tokens.len(); |
| 73 | + if len > 0 { |
| 74 | + self.tokens[len - 1].set_children(); |
| 75 | + } |
| 76 | + |
| 77 | + self.tokens.push(Token::new(siblings)); |
| 78 | + self |
| 79 | + } |
| 80 | + |
| 81 | + /// Removes the last layer of indentation |
| 82 | + pub fn deindent(&mut self) -> &mut Self { |
| 83 | + self.tokens.pop(); |
| 84 | + self |
| 85 | + } |
| 86 | +} |
0 commit comments