bitsy_parser/
position.rs

1use std::fmt;
2
3#[derive(Clone, Debug, Eq, PartialEq)]
4pub struct Position {
5    pub x: u8,
6    pub y: u8,
7}
8
9impl Position {
10    pub fn from_str(s: &str) -> Result<Self, crate::Error> {
11        let mut parts = s.split(',');
12
13        let x = parts.next().unwrap();
14        let y = parts.next().unwrap();
15
16        if let (Ok(x), Ok(y)) = (x.parse(), y.parse()) {
17            Ok(Position { x, y })
18        } else {
19            Err(crate::Error::Position)
20        }
21    }
22}
23
24impl fmt::Display for Position {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(f, "{},{}", self.x, self.y)
27    }
28}
29
30#[cfg(test)]
31mod test {
32    use crate::Position;
33
34    #[test]
35    fn position_from_str() {
36        assert_eq!(
37            Position::from_str("4,12").unwrap(),
38            Position { x: 4, y: 12 }
39        );
40    }
41
42    #[test]
43    fn position_from_malformed_str() {
44        assert!(Position::from_str("14,-1").is_err())
45    }
46
47    #[test]
48    fn position_to_string() {
49        assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
50    }
51}