Skip to main content

blockworx_router/
cost.rs

1#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)]
2pub struct Cost(i64);
3
4impl pathfinding::num_traits::Zero for Cost {
5    fn zero() -> Self {
6        COST_ZERO
7    }
8    fn is_zero(&self) -> bool {
9        self.0 == 0
10    }
11}
12
13const UNIT_SCALE: f64 = 16_777_216.0; // 2^24
14
15impl From<Cost> for f64 {
16    fn from(value: Cost) -> Self {
17        value.0 as f64 / UNIT_SCALE
18    }
19}
20
21impl From<f64> for Cost {
22    fn from(value: f64) -> Self {
23        Self((value * UNIT_SCALE) as i64)
24    }
25}
26
27impl From<f32> for Cost {
28    fn from(value: f32) -> Self {
29        Self((value as f64 * UNIT_SCALE) as i64)
30    }
31}
32
33impl Cost {
34    pub const fn new(cost: f64) -> Self {
35        Self((cost * UNIT_SCALE) as i64)
36    }
37}
38
39impl std::ops::AddAssign<Cost> for Cost {
40    fn add_assign(&mut self, rhs: Cost) {
41        self.0 += rhs.0;
42    }
43}
44
45impl std::ops::SubAssign<Cost> for Cost {
46    fn sub_assign(&mut self, rhs: Cost) {
47        self.0 -= rhs.0;
48    }
49}
50
51impl std::ops::Add<Cost> for Cost {
52    type Output = Self;
53
54    fn add(self, rhs: Cost) -> Self::Output {
55        Self(self.0 + rhs.0)
56    }
57}
58
59impl std::ops::Sub<Cost> for Cost {
60    type Output = Self;
61
62    fn sub(self, rhs: Cost) -> Self::Output {
63        Self(self.0 - rhs.0)
64    }
65}
66
67impl std::ops::Mul<Cost> for i64 {
68    type Output = Cost;
69
70    fn mul(self, rhs: Cost) -> Self::Output {
71        Cost(self * rhs.0)
72    }
73}
74
75impl std::ops::Mul<f64> for Cost {
76    type Output = Cost;
77
78    fn mul(self, rhs: f64) -> Self::Output {
79        Cost((self.0 as f64 * rhs) as i64)
80    }
81}
82
83pub const COST_ZERO: Cost = Cost(0);
84
85impl std::fmt::Display for Cost {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        write!(f, "{:.2}", self.0 as f64 / UNIT_SCALE)
88    }
89}