summaryrefslogtreecommitdiff
path: root/src/table.rs
blob: cc01ffcbbf553561b43d4a6ecf489cf8a452337c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use crate::Line;

pub struct Table {
    pub columns: Vec<Column>,
    pub rows: Vec<Vec<Line>>,
}

pub struct Column {
    pub name: Line,
    pub alignment: Alignment,
}

pub enum Alignment {
    Left,
    Center,
    Right,
}
impl Alignment {
    pub fn from_str(s: &str) -> Result<Self, ()> {
        let mut start = false;
        let mut end = false;
        for (i, c) in s.chars().enumerate() {
            if c == ':' {
                if i == 0 {
                    start = true;
                } else if i == s.len() - 1 {
                    end = true;
                } else {
                    return Err(());
                }
            } else if c != '-' {
                return Err(());
            }
        }
        Ok(match (start, end) {
            (false, false) => Self::Left,
            (true, false) => Self::Left,
            (false, true) => Self::Right,
            (true, true) => Self::Center,
        })
    }
}
impl std::fmt::Display for Alignment {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        f.write_str(match self {
            Self::Left => "left",
            Self::Center => "center",
            Self::Right => "right",
        })
    }
}
impl std::fmt::Debug for Alignment {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        f.write_str(match self {
            Self::Left => "Left",
            Self::Center => "Center",
            Self::Right => "Right",
        })
    }
}