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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use std::{cmp, ops};

use anyhow::Result;
use instant::Instant;
use serde::{Deserialize, Serialize};

use abstutil::elapsed_seconds;

use crate::{trim_f64, Distance, Speed, UnitFmt};

/// A duration, in seconds. Can be negative.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct Duration(f64);

// By construction, Duration is a finite f64 with trimmed precision.
impl Eq for Duration {}
impl Ord for Duration {
    fn cmp(&self, other: &Duration) -> cmp::Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl Duration {
    pub const ZERO: Duration = Duration::const_seconds(0.0);
    const EPSILON: Duration = Duration::const_seconds(0.0001);

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

        Duration(trim_f64(value))
    }

    /// Creates a duration in minutes.
    pub fn minutes(mins: usize) -> Duration {
        Duration::seconds((mins as f64) * 60.0)
    }

    /// Creates a duration in hours.
    pub fn hours(hours: usize) -> Duration {
        Duration::seconds((hours as f64) * 3600.0)
    }

    /// Creates a duration in minutes.
    pub fn f64_minutes(mins: f64) -> Duration {
        Duration::seconds(mins * 60.0)
    }

    pub const fn const_seconds(value: f64) -> Duration {
        Duration(value)
    }

    pub(crate) fn to_u64(self) -> u64 {
        (self.0 / Duration::EPSILON.0) as u64
    }

    pub(crate) fn from_u64(x: u64) -> Duration {
        (x as f64) * Duration::EPSILON
    }

    /// Returns the duration in seconds. Prefer working in typesafe `Duration`s.
    // TODO Remove if possible.
    pub fn inner_seconds(self) -> f64 {
        self.0
    }

    /// Splits the duration into (hours, minutes, seconds, centiseconds).
    // TODO Could share some of this with Time -- the representations are the same
    fn get_parts(self) -> (usize, usize, usize, usize) {
        // Force positive
        let mut remainder = self.inner_seconds().abs();
        let hours = (remainder / 3600.0).floor();
        remainder -= hours * 3600.0;
        let minutes = (remainder / 60.0).floor();
        remainder -= minutes * 60.0;
        let seconds = remainder.floor();
        remainder -= seconds;
        let centis = (remainder / 0.1).floor();

        (
            hours as usize,
            minutes as usize,
            seconds as usize,
            centis as usize,
        )
    }

    /// Parses a duration such as "3:00" to `Duration::minutes(3)`.
    // TODO This is NOT the inverse of Display!
    pub fn parse(string: &str) -> Result<Duration> {
        let parts: Vec<&str> = string.split(':').collect();
        if parts.is_empty() {
            bail!("Duration {}: no :'s", string);
        }

        let mut seconds: f64 = 0.0;
        if parts.last().unwrap().contains('.') {
            let last_parts: Vec<&str> = parts.last().unwrap().split('.').collect();
            if last_parts.len() != 2 {
                bail!("Duration {}: no . in last part", string);
            }
            seconds += last_parts[1].parse::<f64>()? / 10.0;
            seconds += last_parts[0].parse::<f64>()?;
        } else {
            seconds += parts.last().unwrap().parse::<f64>()?;
        }

        match parts.len() {
            1 => Ok(Duration::seconds(seconds)),
            2 => {
                seconds += 60.0 * parts[0].parse::<f64>()?;
                Ok(Duration::seconds(seconds))
            }
            3 => {
                seconds += 60.0 * parts[1].parse::<f64>()?;
                seconds += 3600.0 * parts[0].parse::<f64>()?;
                Ok(Duration::seconds(seconds))
            }
            _ => bail!("Duration {}: weird number of parts", string),
        }
    }

    /// If two durations are within this amount, they'll print as if they're the same.
    pub fn epsilon_eq(self, other: Duration) -> bool {
        let eps = Duration::seconds(0.1);
        if self > other {
            self - other < eps
        } else if self < other {
            other - self < eps
        } else {
            true
        }
    }

    /// Returns the duration elapsed from this moment in real time.
    pub fn realtime_elapsed(since: Instant) -> Duration {
        Duration::seconds(elapsed_seconds(since))
    }

    /// Rounds a duration up to the nearest whole number multiple.
    pub fn round_up(self, multiple: Duration) -> Duration {
        let remainder = self % multiple;
        if remainder == Duration::ZERO {
            self
        } else {
            self + multiple - remainder
        }
    }

    /// Returns the duration as a number of minutes, rounded up.
    pub fn num_minutes_rounded_up(self) -> usize {
        let (hrs, mins, secs, rem) = self.get_parts();
        let mut result = mins + 60 * hrs;
        if secs != 0 || rem != 0 {
            result += 1;
        }
        result
    }

    // TODO Do something fancier? http://vis.stanford.edu/papers/tick-labels
    // TODO Unit test me
    /// Returns (rounded max, the boundaries in number of minutes)
    pub fn make_intervals_for_max(self, num_labels: usize) -> (Duration, Vec<usize>) {
        // Example 1: 43 minutes, max 5 labels... raw_mins_per_interval is 8.6
        let raw_mins_per_interval = (self.num_minutes_rounded_up() as f64) / (num_labels as f64);
        // So then this rounded up to 10 minutes
        let mut mins_per_interval = Duration::seconds(60.0 * raw_mins_per_interval)
            .round_up(Duration::minutes(5))
            .num_minutes_rounded_up();

        // Example 2: 8 minutes, max 5 labels... raw_mins_per_interval is 1.6
        // If we're under 25 minutes, this is going to be weird.
        if self < (num_labels as f64) * Duration::minutes(5) {
            // rounded up to 5 mins? 1 min increments
            // up to 10? 2 min increments
            // up to 15? 3
            // up to 20? 4
            // then after that the normal behavior
            mins_per_interval = (self.round_up(Duration::minutes(5)) / (num_labels as f64))
                .num_minutes_rounded_up();
        }

        let max = (num_labels as f64) * Duration::minutes(mins_per_interval);
        let labels = (0..=num_labels).map(|i| i * mins_per_interval).collect();

        if max < self {
            panic!(
                "Wait max of {} with {} labels wound up with rounded max of {}",
                self, num_labels, max
            );
        }
        (max, labels)
    }

    /// Describes the duration according to formatting rules.
    pub fn to_string(self, fmt: &UnitFmt) -> String {
        let mut s = String::new();
        if self < Duration::ZERO {
            s = "-".to_string();
        }
        let (hours, minutes, seconds, remainder) = self.get_parts();
        if hours == 0 && minutes == 0 && seconds == 0 && remainder == 0 {
            return "0s".to_string();
        }

        if hours != 0 {
            s = format!("{}{}h", s, hours);
        }
        if hours != 0 || minutes != 0 {
            s = format!("{}{}m", s, minutes);
        }
        if remainder != 0 {
            if fmt.round_durations {
                s = format!("{}{}s", s, seconds);
            } else {
                s = format!("{}{}.{:01}s", s, seconds, remainder);
            }
        } else if seconds != 0 {
            s = format!("{}{}s", s, seconds);
        }
        s
    }
}

impl std::fmt::Display for Duration {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}",
            (*self).to_string(&UnitFmt {
                metric: false,
                round_durations: false
            })
        )
    }
}

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

    fn add(self, other: Duration) -> Duration {
        Duration::seconds(self.0 + other.0)
    }
}

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

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

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

    fn sub(self, other: Duration) -> Duration {
        Duration::seconds(self.0 - other.0)
    }
}

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

    fn mul(self, other: f64) -> Duration {
        Duration::seconds(self.0 * other)
    }
}

// TODO Both of these work. Use a macro or crate to define both, so we don't have to worry about
// order for commutative things like multiplication. :P
impl ops::Mul<Duration> for f64 {
    type Output = Duration;

    fn mul(self, other: Duration) -> Duration {
        Duration::seconds(self * other.0)
    }
}

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

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

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

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

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

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

impl ops::Rem<Duration> for Duration {
    type Output = Duration;

    fn rem(self, other: Duration) -> Duration {
        Duration::seconds(self.0 % other.0)
    }
}

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

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn print_durations() {
        let dont_round = UnitFmt {
            metric: false,
            round_durations: false,
        };
        let round = UnitFmt {
            metric: false,
            round_durations: true,
        };

        assert_eq!("0s", Duration::ZERO.to_string(&dont_round));
        assert_eq!("0s", Duration::seconds(0.001).to_string(&dont_round));
        assert_eq!("1m30.1s", Duration::seconds(90.123).to_string(&dont_round));
        assert_eq!("1m30s", Duration::seconds(90.123).to_string(&round));
    }
}