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
use std::error::Error;

#[derive(Debug, Eq, PartialEq)]
pub struct Position {
    pub x: u8,
    pub y: u8,
}

impl Position {
    #[inline]
    pub(crate) fn from(string: String) -> Result<Position, &'static dyn Error> {
        // e.g. "2,5"
        let xy: Vec<&str> = string.split(',').collect();
        let x = xy[0].parse().expect("Bad x coordinate supplied for Position");

        if xy.len() < 2 {
            panic!("Bad position : {}", string);
        }

        let y = xy[1].parse().expect("Bad y coordinate supplied for Position");

        Ok(Position { x, y })
    }
}

impl ToString for Position {
    #[inline]
    fn to_string(&self) -> String {
        format!("{},{}", self.x, self.y)
    }
}

#[cfg(test)]
mod test {
    use crate::position::Position;

    #[test]
    fn test_position_from_string() {
        assert_eq!(
            Position::from("4,12".to_string()).unwrap(),
            Position { x: 4, y: 12 }
        );
    }

    #[test]
    fn test_position_to_string() {
        assert_eq!(Position { x: 4, y: 12 }.to_string(), "4,12".to_string())
    }
}