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
// SPDX-FileCopyrightText: 2022 Thomas Kramer <code@tkramer.ch>
//
// SPDX-License-Identifier: GPL-3.0-or-later

use num_traits::{Zero, Signed};
use std::ops::{Sub, Add};

/// Point in the Euclidean plane.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Ord, PartialOrd)]
pub struct Point<T> {
    /// x coordinate.
    pub x: T,
    /// y coordinate.
    pub y: T,
}

impl<T> Point<T> {
    /// Create a new point.
    pub fn new(x: T, y: T) -> Self {
        Self { x, y }
    }
}

impl<T> Point<T>
    where T: Copy + Add<Output=T> + Sub<Output=T> + Zero {
    /// Rotate the point around the origin by 90 degrees counter-clock-wise.
    pub fn rotate_ccw90(&self) -> Self {
        Self::new(T::zero() - self.y, self.x)
    }
}

impl<T> Point<T>
    where T: Copy + Add<Output=T> + Sub<Output=T> + Signed {

    /// Compute the manhattan distance between both points.
    pub fn manhattan_distance(&self, other: &Self) -> T {
        let dx = self.x - other.x;
        let dy = self.y - other.y;

        dx.abs() + dy.abs()
    }

    /// Shift the point.
    pub fn translate(&self, (dx, dy): (T, T)) -> Self {
        Point::new(self.x+dx, self.y+dy)
    }
}

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