Skip to main content

utf_railroad/
optional.rs

1use std::fmt;
2use crate::Node;
3
4pub struct Optional(Box<dyn Node>);
5
6impl Optional {
7    pub fn new(node: Box<dyn Node>) -> Self {
8        Self(node)
9    }
10}
11
12impl Node for Optional {
13    fn get_width(&self) -> usize {
14        self.0.get_width() + 2
15    }
16
17    fn get_height(&self) -> usize {
18        self.0.get_height() + 1
19    }
20
21    fn as_str(&self) -> String {
22        let mut ret = String::new();
23
24        let s = self.0.as_str();
25        let lines = s.lines().collect::<Vec<_>>();
26        for y in 0..lines.len() {
27            let sep = if y == 0 { " " } 
28                else if y == 1 { "┬" }
29                else { "│" };
30            ret += sep;
31
32            ret += lines[y];
33
34            ret += sep;
35            ret += "\n";
36        }
37
38        ret += "╰";
39        for _ in 0..self.get_width()-2 { ret += "─" }
40        ret += "╯";
41        ret
42    }
43}
44
45impl fmt::Display for Optional {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "{}", self.as_str())
48    }
49}