paiagram/units/
distance.rs

1use derive_more::{Add, AddAssign, Sub, SubAssign};
2#[derive(Debug, Clone, Copy, Add, AddAssign, Sub, SubAssign)]
3pub struct Distance(pub i32);
4
5impl Distance {
6    #[inline]
7    pub fn from_km(km: f32) -> Self {
8        Distance((km * 1000.0).round() as i32)
9    }
10    #[inline]
11    pub fn from_m(m: i32) -> Self {
12        Distance(m)
13    }
14}
15
16impl std::fmt::Display for Distance {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        if self.0 <= 1000 {
19            write!(f, "{}m", self.0)
20        } else {
21            write!(f, "{}.{:03}km", self.0 / 1000, self.0 % 1000)
22        }
23    }
24}
25
26impl std::ops::Mul<i32> for Distance {
27    type Output = Self;
28    fn mul(self, rhs: i32) -> Self::Output {
29        Self(self.0 * rhs)
30    }
31}
32
33impl std::ops::MulAssign<i32> for Distance {
34    fn mul_assign(&mut self, rhs: i32) {
35        self.0 *= rhs;
36    }
37}
38
39impl std::ops::Mul<f32> for Distance {
40    type Output = Self;
41    fn mul(self, rhs: f32) -> Self::Output {
42        Self((self.0 as f32 * rhs).round() as i32)
43    }
44}
45
46impl std::ops::MulAssign<f32> for Distance {
47    fn mul_assign(&mut self, rhs: f32) {
48        self.0 = (self.0 as f32 * rhs).round() as i32;
49    }
50}
51
52impl std::ops::Div<i32> for Distance {
53    type Output = Self;
54    fn div(self, rhs: i32) -> Self::Output {
55        Self(self.0 / rhs)
56    }
57}
58
59impl std::ops::DivAssign<i32> for Distance {
60    fn div_assign(&mut self, rhs: i32) {
61        self.0 /= rhs
62    }
63}
64
65impl std::ops::Div<f32> for Distance {
66    type Output = Self;
67    fn div(self, rhs: f32) -> Self::Output {
68        Self((self.0 as f32 / rhs).round() as i32)
69    }
70}
71
72impl std::ops::DivAssign<f32> for Distance {
73    fn div_assign(&mut self, rhs: f32) {
74        self.0 = (self.0 as f32 / rhs).round() as i32;
75    }
76}