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
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use std::{cmp, f64, fmt, ops};

use serde::{Deserialize, Serialize};

use crate::{deserialize_f64, serialize_f64, trim_f64, Duration, Speed, UnitFmt};

/// A distance, in meters. Can be negative.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Distance(
    #[serde(serialize_with = "serialize_f64", deserialize_with = "deserialize_f64")] f64,
);

// By construction, Distance is a finite f64 with trimmed precision.
impl Eq for Distance {}

#[allow(clippy::derive_ord_xor_partial_ord)] // false positive
impl Ord for Distance {
    fn cmp(&self, other: &Distance) -> cmp::Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl Distance {
    pub const ZERO: Distance = Distance::const_meters(0.0);

    /// Creates a distance in meters.
    pub fn meters(value: f64) -> Distance {
        if !value.is_finite() {
            panic!("Bad Distance {}", value);
        }

        Distance(trim_f64(value))
    }

    // TODO Can't panic inside a const fn, seemingly. Don't pass in anything bad!
    pub const fn const_meters(value: f64) -> Distance {
        Distance(value)
    }

    /// Creates a distance in inches.
    pub fn inches(value: f64) -> Distance {
        Distance::meters(0.0254 * value)
    }

    /// Creates a distance in miles.
    pub fn miles(value: f64) -> Distance {
        Distance::meters(1609.34 * value)
    }

    /// Creates a distance in centimeters.
    pub fn centimeters(value: usize) -> Distance {
        Distance::meters((value as f64) / 100.0)
    }

    /// Creates a distance in feet.
    pub fn feet(value: f64) -> Distance {
        Distance::meters(value * 0.3048)
    }

    /// Returns the absolute value of this distance.
    pub fn abs(self) -> Distance {
        if self.0 > 0.0 {
            self
        } else {
            Distance(-self.0)
        }
    }

    /// Returns the square root of this distance.
    pub fn sqrt(self) -> Distance {
        Distance::meters(self.0.sqrt())
    }

    /// Returns the distance in meters. Prefer to work with type-safe `Distance`s.
    // TODO Remove if possible.
    pub fn inner_meters(self) -> f64 {
        self.0
    }

    /// Returns the distance in feet.
    pub fn to_feet(self) -> f64 {
        self.0 * 3.28084
    }

    /// Describes the distance according to formatting rules. Rounds to 1 decimal place for both
    /// small (feet and meters) and large (miles and kilometers) units.
    pub fn to_string(self, fmt: &UnitFmt) -> String {
        if fmt.metric {
            if self.0 < 1000.0 {
                format!("{}m", (self.0 * 10.0).round() / 10.0)
            } else {
                let km = self.0 / 1000.0;
                format!("{}km", (km * 10.0).round() / 10.0)
            }
        } else {
            let feet = self.to_feet();
            let miles = feet / 5280.0;
            if miles >= 0.1 {
                format!("{} miles", (miles * 10.0).round() / 10.0)
            } else {
                format!("{} ft", (feet * 10.0).round() / 10.0)
            }
        }
    }

    /// Calculates a percentage, usually in [0.0, 1.0], of self / other. If the denominator is
    /// zero, returns 0%.
    pub fn safe_percent(self, other: Distance) -> f64 {
        if other == Distance::ZERO {
            return 0.0;
        }
        self / other
    }
}

impl fmt::Display for Distance {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}m", self.0)
    }
}

impl ops::Add for Distance {
    type Output = Distance;

    fn add(self, other: Distance) -> Distance {
        Distance::meters(self.0 + other.0)
    }
}

impl ops::AddAssign for Distance {
    fn add_assign(&mut self, other: Distance) {
        *self = *self + other;
    }
}

impl ops::Sub for Distance {
    type Output = Distance;

    fn sub(self, other: Distance) -> Distance {
        Distance::meters(self.0 - other.0)
    }
}

impl ops::Neg for Distance {
    type Output = Distance;

    fn neg(self) -> Distance {
        Distance::meters(-self.0)
    }
}

impl ops::SubAssign for Distance {
    fn sub_assign(&mut self, other: Distance) {
        *self = *self - other;
    }
}

impl ops::Mul<f64> for Distance {
    type Output = Distance;

    fn mul(self, scalar: f64) -> Distance {
        Distance::meters(self.0 * scalar)
    }
}

impl ops::Mul<Distance> for f64 {
    type Output = Distance;

    fn mul(self, other: Distance) -> Distance {
        Distance::meters(self * other.0)
    }
}

impl ops::Div<Distance> for Distance {
    type Output = f64;

    fn div(self, other: Distance) -> f64 {
        if other == Distance::ZERO {
            panic!("Can't divide {} / {}", self, other);
        }
        self.0 / other.0
    }
}

impl ops::Div<f64> for Distance {
    type Output = Distance;

    fn div(self, scalar: f64) -> Distance {
        if scalar == 0.0 {
            panic!("Can't divide {} / {}", self, scalar);
        }
        Distance::meters(self.0 / scalar)
    }
}

impl ops::Div<Speed> for Distance {
    type Output = Duration;

    fn div(self, other: Speed) -> Duration {
        if other == Speed::ZERO {
            panic!("Can't divide {} / 0 mph", self);
        }
        Duration::seconds(self.0 / other.inner_meters_per_second())
    }
}

impl std::iter::Sum for Distance {
    fn sum<I>(iter: I) -> Distance
    where
        I: Iterator<Item = Distance>,
    {
        let mut sum = Distance::ZERO;
        for x in iter {
            sum += x;
        }
        sum
    }
}

impl Default for Distance {
    fn default() -> Distance {
        Distance::ZERO
    }
}