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
use anyhow::Error;
use derive_more::{Deref, Display, From, Into};
use serde::{Deserialize, Serialize};
use std::{convert::TryFrom, f64::consts::PI};

use crate::angle::Angle;

/// Direction in degrees
#[derive(
    Into, Debug, PartialEq, Copy, Clone, PartialOrd, Serialize, Deserialize, Display, Deref, From,
)]
pub struct Direction(Angle);

impl From<f64> for Direction {
    fn from(item: f64) -> Self {
        Self(Angle::from_deg(item))
    }
}

impl Direction {
    pub fn from_deg(deg: f64) -> Self {
        Self(Angle::from_deg(deg))
    }

    pub fn from_radian(rad: f64) -> Self {
        Self(Angle::from_radian(rad))
    }
}

#[cfg(test)]
mod tests {
    use approx::assert_abs_diff_eq;
    use std::f64::consts::PI;

    use crate::direction::Direction;

    #[test]
    fn test_direction() {
        assert_eq!(Direction::from_deg(90.), Direction::from_deg(90. + 360.));
        assert_abs_diff_eq!(
            Direction::from_deg(90.).deg(),
            Direction::from_radian(PI / 2.).deg()
        );
        assert_abs_diff_eq!(
            Direction::from_deg(90.).deg(),
            Direction::from_radian(PI / 2. + 2. * PI).deg()
        );
        assert_abs_diff_eq!(
            Direction::from_deg(90.).radian(),
            Direction::from_radian(PI / 2.).radian()
        );
        assert_eq!(Direction::from_deg(-90.), Direction::from_deg(-90. + 360.));
        assert_abs_diff_eq!(
            Direction::from_deg(-90.).deg(),
            Direction::from_radian(-1.0 * PI / 2.).deg()
        );
        assert_eq!(
            Direction::from_deg(-90.),
            Direction::from_radian(-1.0 * PI / 2. + 2. * PI)
        );
        assert_abs_diff_eq!(
            Direction::from_deg(-90.).radian(),
            Direction::from_radian(-1.0 * PI / 2.).radian()
        );
    }
}