Skip to main content

waft_embedder/
signed_duration.rs

1//! dart:core `Duration`, where it can be negative: a time zone's offset west of UTC, the
2//! difference between two instants. Everywhere else Waft takes `std::time::Duration`, which Dart's
3//! non-negative durations map to.
4
5use std::fmt;
6use std::ops::{Add, Neg, Sub};
7
8/// A span of time, such as 27 days, 4 hours, 12 minutes and 3 seconds, which may be negative.
9///
10/// Dart's `Duration`, kept beside `std::time::Duration` under its own name: the framework's
11/// durations are never negative and take std's, and a name shared with std's would shadow it in
12/// every `use waft::*`.
13///
14/// ```
15/// # use waft_embedder::SignedDuration;
16/// let west = SignedDuration::from_hours(-8);
17/// assert_eq!(west.in_minutes(), -480);
18/// assert_eq!(west.to_string(), "-8:00:00.000000");
19/// ```
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub struct SignedDuration {
22    microseconds: i64,
23}
24
25const MICROSECONDS_PER_MILLISECOND: i64 = 1000;
26const MICROSECONDS_PER_SECOND: i64 = 1_000_000;
27const MICROSECONDS_PER_MINUTE: i64 = 60 * MICROSECONDS_PER_SECOND;
28const MICROSECONDS_PER_HOUR: i64 = 60 * MICROSECONDS_PER_MINUTE;
29const MICROSECONDS_PER_DAY: i64 = 24 * MICROSECONDS_PER_HOUR;
30
31impl SignedDuration {
32    /// An empty duration, representing zero time.
33    pub const ZERO: SignedDuration = SignedDuration { microseconds: 0 };
34
35    /// Dart's `Duration(days: ..)`.
36    pub const fn from_days(days: i64) -> SignedDuration {
37        SignedDuration::from_microseconds(days * MICROSECONDS_PER_DAY)
38    }
39
40    /// Dart's `Duration(hours: ..)`.
41    pub const fn from_hours(hours: i64) -> SignedDuration {
42        SignedDuration::from_microseconds(hours * MICROSECONDS_PER_HOUR)
43    }
44
45    /// Dart's `Duration(minutes: ..)`.
46    pub const fn from_minutes(minutes: i64) -> SignedDuration {
47        SignedDuration::from_microseconds(minutes * MICROSECONDS_PER_MINUTE)
48    }
49
50    /// Dart's `Duration(seconds: ..)`.
51    pub const fn from_seconds(seconds: i64) -> SignedDuration {
52        SignedDuration::from_microseconds(seconds * MICROSECONDS_PER_SECOND)
53    }
54
55    /// Dart's `Duration(milliseconds: ..)`.
56    pub const fn from_milliseconds(milliseconds: i64) -> SignedDuration {
57        SignedDuration::from_microseconds(milliseconds * MICROSECONDS_PER_MILLISECOND)
58    }
59
60    /// Dart's `Duration(microseconds: ..)`.
61    pub const fn from_microseconds(microseconds: i64) -> SignedDuration {
62        SignedDuration { microseconds }
63    }
64
65    /// The number of entire days spanned by this duration, truncated toward zero.
66    pub const fn in_days(&self) -> i64 {
67        self.microseconds / MICROSECONDS_PER_DAY
68    }
69
70    /// The number of entire hours spanned by this duration, truncated toward zero.
71    pub const fn in_hours(&self) -> i64 {
72        self.microseconds / MICROSECONDS_PER_HOUR
73    }
74
75    /// The number of entire minutes spanned by this duration, truncated toward zero.
76    pub const fn in_minutes(&self) -> i64 {
77        self.microseconds / MICROSECONDS_PER_MINUTE
78    }
79
80    /// The number of entire seconds spanned by this duration, truncated toward zero.
81    pub const fn in_seconds(&self) -> i64 {
82        self.microseconds / MICROSECONDS_PER_SECOND
83    }
84
85    /// The number of entire milliseconds spanned by this duration, truncated toward zero.
86    pub const fn in_milliseconds(&self) -> i64 {
87        self.microseconds / MICROSECONDS_PER_MILLISECOND
88    }
89
90    /// The number of whole microseconds spanned by this duration.
91    pub const fn in_microseconds(&self) -> i64 {
92        self.microseconds
93    }
94
95    /// Whether this duration is negative.
96    pub const fn is_negative(&self) -> bool {
97        self.microseconds < 0
98    }
99
100    /// A new duration with the same length as this one, but positive.
101    pub const fn abs(&self) -> SignedDuration {
102        SignedDuration::from_microseconds(self.microseconds.abs())
103    }
104}
105
106impl Neg for SignedDuration {
107    type Output = SignedDuration;
108
109    fn neg(self) -> SignedDuration {
110        SignedDuration::from_microseconds(-self.microseconds)
111    }
112}
113
114impl Add for SignedDuration {
115    type Output = SignedDuration;
116
117    fn add(self, other: SignedDuration) -> SignedDuration {
118        SignedDuration::from_microseconds(self.microseconds + other.microseconds)
119    }
120}
121
122impl Sub for SignedDuration {
123    type Output = SignedDuration;
124
125    fn sub(self, other: SignedDuration) -> SignedDuration {
126        SignedDuration::from_microseconds(self.microseconds - other.microseconds)
127    }
128}
129
130/// A non-negative std duration as a signed one, as every Dart `Duration` the framework takes is.
131impl From<std::time::Duration> for SignedDuration {
132    fn from(duration: std::time::Duration) -> SignedDuration {
133        SignedDuration::from_microseconds(
134            i64::try_from(duration.as_micros()).expect("a duration within range"),
135        )
136    }
137}
138
139/// Dart's `Duration.toString`: hours, minutes, seconds and microseconds, as `-8:00:00.000000`.
140impl fmt::Display for SignedDuration {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        let sign = if self.is_negative() { "-" } else { "" };
143        let microseconds = self.microseconds.unsigned_abs();
144        let per_hour = MICROSECONDS_PER_HOUR.unsigned_abs();
145        let per_minute = MICROSECONDS_PER_MINUTE.unsigned_abs();
146        let per_second = MICROSECONDS_PER_SECOND.unsigned_abs();
147        let hours = microseconds / per_hour;
148        let minutes = microseconds % per_hour / per_minute;
149        let seconds = microseconds % per_minute / per_second;
150        let micros = microseconds % per_second;
151        write!(f, "{sign}{hours}:{minutes:02}:{seconds:02}.{micros:06}")
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    /// `core/duration_test.dart`'s `toString` cases.
160    #[test]
161    fn to_string_follows_dart() {
162        assert_eq!(SignedDuration::ZERO.to_string(), "0:00:00.000000");
163        assert_eq!(SignedDuration::from_hours(1).to_string(), "1:00:00.000000");
164        assert_eq!(
165            (SignedDuration::from_hours(-8) - SignedDuration::from_minutes(30)).to_string(),
166            "-8:30:00.000000"
167        );
168        assert_eq!(
169            SignedDuration::from_microseconds(-1).to_string(),
170            "-0:00:00.000001"
171        );
172        assert_eq!(SignedDuration::from_days(2).to_string(), "48:00:00.000000");
173    }
174
175    #[test]
176    fn the_in_getters_truncate_toward_zero() {
177        let d = SignedDuration::from_seconds(-90);
178        assert_eq!((d.in_minutes(), d.in_seconds()), (-1, -90));
179        assert_eq!(d.abs().in_minutes(), 1);
180        assert_eq!(-d, SignedDuration::from_seconds(90));
181        assert!(d.is_negative());
182    }
183}