summaryrefslogtreecommitdiff
path: root/src/values/alignment.rs
blob: 7e9fcaba8a33e8926e692c8ee3abecd8f74de0a4 (plain)
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
61
62
63
64
65
use iced::Alignment;

use super::Value;

#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum ParseAlignmentError {
    #[error("cannot parse rotation from empty string")]
    Empty,
    #[error("invalid variant")]
    InvalidVariant,
}

impl Value for Alignment {
    type Err = ParseAlignmentError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();

        if s.is_empty() {
            return Err(ParseAlignmentError::Empty);
        }

        match s {
            "start" => Ok(Self::Start),
            "center" => Ok(Self::Center),
            "end" => Ok(Self::End),
            _ => Err(ParseAlignmentError::InvalidVariant),
        }
    }

    fn to_string(&self) -> String {
        match self {
            Self::Start => String::from("start"),
            Self::Center => String::from("center"),
            Self::End => String::from("end"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_parse_with_spaces() {
        assert_eq!(Alignment::from_str("  start"), Ok(Alignment::Start));

        assert_eq!(Alignment::from_str("   center   "), Ok(Alignment::Center));

        assert_eq!(Alignment::from_str("end "), Ok(Alignment::End))
    }

    #[test]
    fn cant_parse_invalid_variant() {
        assert_eq!(
            Alignment::from_str("middle"),
            Err(ParseAlignmentError::InvalidVariant)
        )
    }

    #[test]
    fn cant_parse_empty_string() {
        assert_eq!(Alignment::from_str(" "), Err(ParseAlignmentError::Empty))
    }
}