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
use std::convert::TryFrom;

use super::Point;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    Right,
    Left,
    Up,
    Down,
}

impl Direction {
    /// `(dx, dy)`, for `Right` is `+x` and `Up` is `+y`
    pub fn deltas(self) -> (i32, i32) {
        use Direction::*;
        match self {
            Up => (0, 1),
            Down => (0, -1),
            Right => (1, 0),
            Left => (-1, 0),
        }
    }

    pub fn turn_right(self) -> Direction {
        use Direction::*;
        match self {
            Up => Right,
            Right => Down,
            Down => Left,
            Left => Up,
        }
    }

    pub fn turn_left(self) -> Direction {
        use Direction::*;
        match self {
            Up => Left,
            Left => Down,
            Down => Right,
            Right => Up,
        }
    }

    pub fn reverse(self) -> Direction {
        use Direction::*;
        match self {
            Up => Down,
            Left => Right,
            Down => Up,
            Right => Left,
        }
    }

    /// Iterate over the four orthogonal directions
    pub fn iter() -> impl Iterator<Item = Direction> {
        use Direction::*;
        [Up, Down, Left, Right].iter().copied()
    }

    /// Iterate over the four diagonal direction-pairs
    ///
    /// Each pair takes the form `(vertical, horizontal)`.
    pub fn iter_diag() -> impl Iterator<Item = (Direction, Direction)> {
        use Direction::*;
        [(Up, Left), (Up, Right), (Down, Left), (Down, Right)]
            .iter()
            .copied()
    }
}

impl Default for Direction {
    fn default() -> Self {
        Direction::Up
    }
}

/// Inverse of [`Direction::deltas`].
impl TryFrom<Point> for Direction {
    type Error = ();

    fn try_from(value: Point) -> Result<Self, Self::Error> {
        match value {
            Point { x: 0, y: 1 } => Ok(Direction::Up),
            Point { x: 0, y: -1 } => Ok(Direction::Down),
            Point { x: 1, y: 0 } => Ok(Direction::Right),
            Point { x: -1, y: 0 } => Ok(Direction::Left),
            _ => Err(()),
        }
    }
}