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
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::{
    fmt,
    ops::{Add, AddAssign, Sub, SubAssign},
    str::FromStr,
};

/// The coordinate key to a specific [`Grid`](crate::grid::Grid) cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Coord {
    pub x: i32,
    pub y: i32,
}

impl Coord {
    pub fn new(x: i32, y: i32) -> Self {
        Coord { x, y }
    }
}

impl Add<Coord> for Coord {
    type Output = Coord;

    fn add(self, rhs: Coord) -> Self::Output {
        Coord::new(self.x + rhs.x, self.y + rhs.y)
    }
}

impl AddAssign<Coord> for Coord {
    fn add_assign(&mut self, rhs: Coord) {
        self.x += rhs.x;
        self.y += rhs.y;
    }
}

impl Sub<Coord> for Coord {
    type Output = Coord;

    fn sub(self, rhs: Coord) -> Self::Output {
        Coord::new(self.x - rhs.x, self.y - rhs.y)
    }
}

impl SubAssign<Coord> for Coord {
    fn sub_assign(&mut self, rhs: Coord) {
        self.x -= rhs.x;
        self.y -= rhs.y;
    }
}

impl From<(i32, i32)> for Coord {
    fn from((x, y): (i32, i32)) -> Self {
        Coord::new(x, y)
    }
}

impl From<Coord> for (i32, i32) {
    fn from(Coord { x, y }: Coord) -> Self {
        (x, y)
    }
}

#[derive(Debug, PartialEq)]
pub enum ParseCoordError {
    InvalidDimensions,
    InvalidDigit,
}

impl FromStr for Coord {
    type Err = ParseCoordError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Parse standard `(x, y)` format.
        let xy_vec = s
            .trim_matches(|p| p == '(' || p == ')')
            .split(',')
            .map(|s| s.trim())
            .collect::<Vec<_>>();

        if xy_vec.len() != 2 {
            return Err(ParseCoordError::InvalidDimensions);
        }

        let parsed_xy = xy_vec
            .iter()
            .map(|x| x.parse::<i32>().map_err(|_| ParseCoordError::InvalidDigit))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Coord::new(parsed_xy[0], parsed_xy[1]))
    }
}

impl fmt::Display for Coord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

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

    #[test]
    fn coord_parse() {
        let coord_str = "(0, 0)";
        // Ill-formatted but parseable coord strings
        // TODO: Restrict accepted coord format
        let bad_parens_coord_str = ")0, 0(";
        let none_parens_coord_str = "0, 0";
        assert_eq!(coord_str.parse(), Ok(Coord::new(0, 0)));
        assert_eq!(bad_parens_coord_str.parse(), Ok(Coord::new(0, 0)));
        assert_eq!(none_parens_coord_str.parse(), Ok(Coord::new(0, 0)));
    }

    #[test]
    fn neg_coord_parse() {
        let coord_str = "(-1, -1)";
        assert_eq!(coord_str.parse(), Ok(Coord::new(-1, -1)));
    }

    #[test]
    fn flexible_spacing_coord_parse() {
        let coord_str = "(0   , 0   )";
        assert_eq!(coord_str.parse(), Ok(Coord::new(0, 0)));
    }

    #[test]
    fn coord_parse_invalid_digit() {
        let coord_str = "(x, y)";
        let newline_coord_str = "(0, 0)\n";
        assert!(coord_str.parse::<Coord>() == Err(ParseCoordError::InvalidDigit));
        assert!(newline_coord_str.parse::<Coord>() == Err(ParseCoordError::InvalidDigit));
    }

    #[test]
    fn coord_parse_invalid_dimensions() {
        let insufficient_coord_str = "(0)";
        let excessive_coord_str = "(1, 2, 3)";
        assert!(insufficient_coord_str.parse::<Coord>() == Err(ParseCoordError::InvalidDimensions));
        assert!(excessive_coord_str.parse::<Coord>() == Err(ParseCoordError::InvalidDimensions));
    }
}