lexe-common 0.1.25

Lexe common types, traits, and utilities
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use std::{
    fmt::{self, Display},
    str::FromStr,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use serde::{Serialize, de};

/// [`Display`]s a [`Duration`] in ms with 3 decimal places, e.g. "123.456ms".
///
/// Useful to log elapsed times in a consistent unit, as [`Duration`]'s default
/// implementation will go with seconds, ms, nanos etc depending on the value.
pub struct DisplayMs(pub Duration);

impl Display for DisplayMs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ms = self.0.as_secs_f64() * 1000.0;
        write!(f, "{ms:.3}ms")
    }
}

/// A timestamp in milliseconds since the UNIX epoch (January 1, 1970).
/// Serialized as a non-negative integer.
//
// - Internally represented by a non-negative [`i64`] to ease interoperability
//   with some platforms we use which don't support unsigned ints well (Postgres
//   and Dart/Flutter).
// - Can represent any time from January 1st, 1970 00:00:00.000 UTC to roughly
//   292 million years in the future.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[derive(Serialize)]
pub struct TimestampMs(i64);

/// Errors that can occur when attempting to construct a [`TimestampMs`].
#[derive(Debug, Eq, PartialEq, thiserror::Error)]
pub enum Error {
    #[error("timestamp value is negative")]
    Negative,

    #[error("timestamp is more than 292 million years past epoch")]
    TooLarge,

    #[error("timestamp is before January 1st, 1970")]
    BeforeEpoch,

    #[error("failed to parse timestamp: {0}")]
    Parse(#[from] std::num::ParseIntError),
}

impl TimestampMs {
    pub const MIN: Self = TimestampMs(0);
    pub const MAX: Self = TimestampMs(i64::MAX);

    /// Creates a new [`TimestampMs`] from the current [`SystemTime`].
    ///
    /// Panics if the current time is not within bounds.
    pub fn now() -> Self {
        Self::try_from(SystemTime::now()).unwrap()
    }

    /// Get this unix timestamp as an [`i64`] in milliseconds from unix epoch.
    #[inline]
    pub fn to_i64(self) -> i64 {
        self.0
    }

    /// Get this unix timestamp as a [`u64`] in milliseconds from unix epoch.
    #[inline]
    pub fn to_u64(self) -> u64 {
        debug_assert!(self.0 >= 0);
        self.0 as u64
    }

    /// Construct [`TimestampMs`] from seconds since Unix epoch.
    pub fn from_secs(secs: u64) -> Result<Self, Error> {
        Self::try_from(Duration::from_secs(secs))
    }

    /// Infallibly construct [`TimestampMs`] from seconds since Unix epoch.
    pub fn from_secs_u32(secs: u32) -> Self {
        Self(i64::from(secs) * 1000)
    }

    /// Construct [`TimestampMs`] from milliseconds since Unix epoch.
    pub fn from_millis(millis: u64) -> Result<Self, Error> {
        Self::try_from(Duration::from_millis(millis))
    }

    /// Construct [`TimestampMs`] from [`Duration`] since Unix epoch.
    pub fn from_duration(dur_since_epoch: Duration) -> Result<Self, Error> {
        i64::try_from(dur_since_epoch.as_millis())
            .map(Self)
            .map_err(|_| Error::TooLarge)
    }

    /// Construct [`TimestampMs`] from a [`SystemTime`].
    pub fn from_system_time(system_time: SystemTime) -> Result<Self, Error> {
        let duration = system_time
            .duration_since(UNIX_EPOCH)
            .map_err(|_| Error::BeforeEpoch)?;
        Self::try_from(duration)
    }

    /// Quickly create a dummy timestamp which can be used in tests.
    #[cfg(any(test, feature = "test-utils"))]
    pub fn from_u8(i: u8) -> Self {
        Self(i64::from(i))
    }

    /// Get this unix timestamp as a [`u64`] in milliseconds from unix epoch.
    #[inline]
    pub fn to_millis(self) -> u64 {
        self.to_u64()
    }

    /// Get this unix timestamp as a [`u64`] in seconds from unix epoch.
    #[inline]
    pub fn to_secs(self) -> u64 {
        Duration::from_millis(self.to_millis()).as_secs()
    }

    /// Get this unix timestamp as a [`Duration`] from the unix epoch.
    #[inline]
    pub fn to_duration(self) -> Duration {
        Duration::from_millis(self.to_millis())
    }

    /// Get this unix timestamp as a [`SystemTime`].
    #[inline]
    pub fn to_system_time(self) -> SystemTime {
        // This add is infallible -- it doesn't panic even with Self::MAX.
        UNIX_EPOCH + self.to_duration()
    }

    pub fn checked_add(self, duration: Duration) -> Option<Self> {
        let dur_ms = i64::try_from(duration.as_millis()).ok()?;
        let added = self.0.checked_add(dur_ms)?;
        Self::try_from(added).ok()
    }

    pub fn checked_sub(self, duration: Duration) -> Option<Self> {
        let dur_ms = i64::try_from(duration.as_millis()).ok()?;
        let subtracted = self.0.checked_sub(dur_ms)?;
        Self::try_from(subtracted).ok()
    }

    pub fn saturating_add(self, duration: Duration) -> Self {
        self.checked_add(duration).unwrap_or(Self::MAX)
    }

    pub fn saturating_sub(self, duration: Duration) -> Self {
        self.checked_sub(duration).unwrap_or(Self::MIN)
    }

    /// Returns the [`Duration`] elapsed from `earlier` to `self`,
    /// or [`None`] if `earlier` is later than `self`.
    pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
        let dur_ms = self.to_u64().checked_sub(earlier.to_u64())?;
        Some(Duration::from_millis(dur_ms))
    }

    /// Returns the [`Duration`] elapsed from `earlier` to `self`,
    /// saturating to [`Duration::ZERO`] if `earlier` is later than `self`.
    pub fn saturating_duration_since(self, earlier: Self) -> Duration {
        let dur_ms = self.to_u64().saturating_sub(earlier.to_u64());
        Duration::from_millis(dur_ms)
    }

    /// Returns the [`Duration`] elapsed since this timestamp,
    /// or [`None`] if it is in the future.
    #[inline]
    pub fn checked_elapsed(self) -> Option<Duration> {
        Self::now().checked_duration_since(self)
    }

    /// Returns the [`Duration`] elapsed since this timestamp,
    /// saturating to [`Duration::ZERO`] if it is in the future.
    #[inline]
    pub fn saturating_elapsed(self) -> Duration {
        Self::now().saturating_duration_since(self)
    }

    /// Formats this timestamp into a human-readable string relative to `now`,
    /// e.g. "just now", "5 minutes ago", "in 3 hours",
    /// "in 2 years and 5 weeks".
    ///
    /// Picks the largest whole unit that fits; weeks and years also carry the
    /// remainder in the next unit down. Sub-second differences in either
    /// direction read as "just now".
    pub fn to_relative_string(self, now: Self) -> String {
        const MINUTE: u64 = 60;
        const HOUR: u64 = 60 * MINUTE;
        const DAY: u64 = 24 * HOUR;
        const WEEK: u64 = 7 * DAY;
        const YEAR: u64 = 365 * DAY;

        /// e.g. "1 week", "3 weeks"
        fn fmt_1_unit(count: u64, unit: &str) -> String {
            let plural = if count == 1 { "" } else { "s" };
            format!("{count} {unit}{plural}")
        }

        /// A count plus its remainder in the next unit down, e.g.
        /// "3 weeks and 2 days". The remainder is omitted when zero.
        fn fmt_2_units(
            count: u64,
            unit: &str,
            rem: u64,
            rem_unit: &str,
        ) -> String {
            let major = fmt_1_unit(count, unit);
            match rem {
                0 => major,
                _ => format!("{major} and {}", fmt_1_unit(rem, rem_unit)),
            }
        }

        let elapsed = now.checked_duration_since(self);
        let secs = match elapsed {
            Some(elapsed) => elapsed.as_secs(),
            None => self.saturating_duration_since(now).as_secs(),
        };

        // Largest whole unit that fits. Weeks and years carry a remainder,
        // since "51 weeks" and "3 years" alone lose too much precision.
        let magnitude = match secs {
            0 => return "just now".to_owned(),
            s if s < MINUTE => fmt_1_unit(s, "second"),
            s if s < HOUR => fmt_1_unit(s / MINUTE, "minute"),
            s if s < DAY => fmt_1_unit(s / HOUR, "hour"),
            s if s < WEEK => fmt_1_unit(s / DAY, "day"),
            s if s < YEAR =>
                fmt_2_units(s / WEEK, "week", (s % WEEK) / DAY, "day"),
            s => fmt_2_units(s / YEAR, "year", (s % YEAR) / WEEK, "week"),
        };

        match elapsed {
            Some(_) => format!("{magnitude} ago"),
            None => format!("in {magnitude}"),
        }
    }

    /// Floors the timestamp to the most recent second.
    #[cfg(test)]
    fn floor_secs(self) -> Self {
        let rem = self.0 % 1000;
        Self(self.0 - rem)
    }
}

impl From<TimestampMs> for Duration {
    #[inline]
    fn from(t: TimestampMs) -> Self {
        t.to_duration()
    }
}

impl From<TimestampMs> for SystemTime {
    #[inline]
    fn from(t: TimestampMs) -> Self {
        t.to_system_time()
    }
}

/// Attempts to convert a [`SystemTime`] into a [`TimestampMs`].
///
/// Returns an error if the [`SystemTime`] is not within bounds.
impl TryFrom<SystemTime> for TimestampMs {
    type Error = Error;
    fn try_from(system_time: SystemTime) -> Result<Self, Self::Error> {
        Self::from_system_time(system_time)
    }
}

/// Attempts to convert a [`Duration`] since the UNIX epoch into a
/// [`TimestampMs`].
///
/// Returns an error if the [`Duration`] is too large.
impl TryFrom<Duration> for TimestampMs {
    type Error = Error;
    fn try_from(dur_since_epoch: Duration) -> Result<Self, Self::Error> {
        Self::from_duration(dur_since_epoch)
    }
}

/// Attempt to convert an [`i64`] in milliseconds since unix epoch into a
/// [`TimestampMs`].
impl TryFrom<i64> for TimestampMs {
    type Error = Error;
    #[inline]
    fn try_from(ms: i64) -> Result<Self, Self::Error> {
        if ms >= Self::MIN.0 {
            Ok(Self(ms))
        } else {
            Err(Error::Negative)
        }
    }
}

impl FromStr for TimestampMs {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(i64::from_str(s)?)
    }
}

impl Display for TimestampMs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        i64::fmt(&self.0, f)
    }
}

impl<'de> de::Deserialize<'de> for TimestampMs {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        i64::deserialize(deserializer)
            .and_then(|x| Self::try_from(x).map_err(de::Error::custom))
    }
}

#[cfg(any(test, feature = "test-utils"))]
mod arbitrary_impl {
    use proptest::{
        arbitrary::Arbitrary,
        strategy::{BoxedStrategy, Strategy},
    };

    use super::*;

    impl Arbitrary for TimestampMs {
        type Parameters = ();
        type Strategy = BoxedStrategy<Self>;
        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
            (Self::MIN.0..Self::MAX.0).prop_map(Self).boxed()
        }
    }
}

#[cfg(test)]
mod test {
    use proptest::{prop_assert_eq, proptest};

    use super::*;
    use crate::test_utils::roundtrip;

    #[test]
    fn timestamp_roundtrip() {
        roundtrip::fromstr_display_roundtrip_proptest::<TimestampMs>();
        roundtrip::json_string_roundtrip_proptest::<TimestampMs>();
    }

    #[test]
    fn deserialize_enforces_nonnegative() {
        // We deserialize from JSON numbers; note that it is NOT e.g. "\"42\""
        assert_eq!(serde_json::from_str::<TimestampMs>("42").unwrap().0, 42);
        assert_eq!(serde_json::from_str::<TimestampMs>("0").unwrap().0, 0);
        assert!(serde_json::from_str::<TimestampMs>("-42").is_err());
    }

    // Value conversions should roundtrip.
    fn assert_conversion_roundtrips(t: TimestampMs) {
        // Seconds
        let floored = t.floor_secs();
        assert_eq!(TimestampMs::from_secs(floored.to_secs()), Ok(floored));
        if let Ok(secs) = u32::try_from(floored.to_secs()) {
            assert_eq!(TimestampMs::from_secs_u32(secs), floored);
        }

        // Milliseconds
        assert_eq!(TimestampMs::from_millis(t.to_millis()), Ok(t));
        assert_eq!(TimestampMs::try_from(t.to_i64()), Ok(t));

        // Duration
        assert_eq!(TimestampMs::from_duration(t.to_duration()), Ok(t));
        assert_eq!(TimestampMs::try_from(t.to_duration()), Ok(t));

        // SystemTime
        assert_eq!(TimestampMs::from_system_time(t.to_system_time()), Ok(t));
        assert_eq!(TimestampMs::try_from(t.to_system_time()), Ok(t));
    }

    #[test]
    fn timestamp_conversions_roundtrip() {
        assert_conversion_roundtrips(TimestampMs::MIN);
        assert_conversion_roundtrips(TimestampMs::MAX);

        proptest!(|(t: TimestampMs)| assert_conversion_roundtrips(t));
    }

    #[test]
    fn timestamp_diff() {
        proptest!(|(ts1: TimestampMs, ts2: TimestampMs)| {
            // Determine which timestamp is lesser/greater
            let (lesser, greater) = if ts1 <= ts2 {
                (ts1, ts2)
            } else {
                (ts2, ts1)
            };

            let diff =
                Duration::from_millis(greater.to_millis() - lesser.to_millis());

            let added = lesser.checked_add(diff).unwrap();
            prop_assert_eq!(added, greater);

            let subtracted = greater.checked_sub(diff).unwrap();
            prop_assert_eq!(subtracted, lesser);
        })
    }

    #[test]
    fn timestamp_saturating_ops() {
        proptest!(|(ts: TimestampMs)| {
            prop_assert_eq!(
                ts.saturating_add(TimestampMs::MAX.to_duration()),
                TimestampMs::MAX
            );
            prop_assert_eq!(
                ts.saturating_sub(TimestampMs::MAX.to_duration()),
                TimestampMs::MIN
            );
            prop_assert_eq!(
                ts.saturating_add(TimestampMs::MIN.to_duration()),
                ts
            );
            prop_assert_eq!(
                ts.saturating_sub(TimestampMs::MIN.to_duration()),
                ts
            );
        })
    }

    #[test]
    fn timestamp_duration_since() {
        proptest!(|(ts1: TimestampMs, ts2: TimestampMs)| {
            let (lesser, greater) =
                if ts1 <= ts2 { (ts1, ts2) } else { (ts2, ts1) };
            let diff =
                Duration::from_millis(greater.to_millis() - lesser.to_millis());

            // `greater` since `lesser` is exactly `diff`.
            prop_assert_eq!(greater.checked_duration_since(lesser), Some(diff));
            prop_assert_eq!(greater.saturating_duration_since(lesser), diff);

            // `lesser` since `greater` underflows: `None` / saturates to
            // `ZERO`, except when equal, where the diff is just `ZERO`.
            let expected_checked = (lesser == greater).then_some(Duration::ZERO);
            prop_assert_eq!(
                lesser.checked_duration_since(greater),
                expected_checked
            );
            prop_assert_eq!(
                lesser.saturating_duration_since(greater),
                Duration::ZERO
            );
        })
    }

    #[test]
    fn timestamp_elapsed() {
        // `now` lies between MIN and MAX, so a min timestamp has elapsed while
        // a max (far-future) timestamp underflows.
        assert!(TimestampMs::MIN.checked_elapsed().is_some());
        assert!(TimestampMs::MIN.saturating_elapsed() > Duration::ZERO);

        assert_eq!(TimestampMs::MAX.checked_elapsed(), None);
        assert_eq!(TimestampMs::MAX.saturating_elapsed(), Duration::ZERO);
    }

    /// Sanity check the relative formatting at every granularity.
    #[test]
    fn relative_string_sanity() {
        const MINUTE: u64 = 60;
        const HOUR: u64 = 60 * MINUTE;
        const DAY: u64 = 24 * HOUR;
        const WEEK: u64 = 7 * DAY;
        const YEAR: u64 = 365 * DAY;

        // (secs away from `now`, past rendering, future rendering)
        let cases = [
            (0, "just now", "just now"),
            (1, "1 second ago", "in 1 second"),
            (59, "59 seconds ago", "in 59 seconds"),
            (MINUTE, "1 minute ago", "in 1 minute"),
            (5 * MINUTE + 30, "5 minutes ago", "in 5 minutes"),
            (HOUR, "1 hour ago", "in 1 hour"),
            (3 * HOUR + 59 * MINUTE, "3 hours ago", "in 3 hours"),
            (DAY + 12 * HOUR, "1 day ago", "in 1 day"),
            (6 * DAY, "6 days ago", "in 6 days"),
            (WEEK, "1 week ago", "in 1 week"),
            (WEEK + DAY, "1 week and 1 day ago", "in 1 week and 1 day"),
            (
                3 * WEEK + 2 * DAY,
                "3 weeks and 2 days ago",
                "in 3 weeks and 2 days",
            ),
            (
                51 * WEEK + 6 * DAY,
                "51 weeks and 6 days ago",
                "in 51 weeks and 6 days",
            ),
            (YEAR, "1 year ago", "in 1 year"),
            (
                YEAR + 5 * WEEK,
                "1 year and 5 weeks ago",
                "in 1 year and 5 weeks",
            ),
            // Remainders below the next unit down are dropped, not rounded.
            (
                2 * YEAR + WEEK + 3 * DAY,
                "2 years and 1 week ago",
                "in 2 years and 1 week",
            ),
            (
                143 * WEEK,
                "2 years and 38 weeks ago",
                "in 2 years and 38 weeks",
            ),
        ];

        let now = TimestampMs::from_secs(100 * YEAR).unwrap();
        for (secs, past, future) in cases {
            let secs = Duration::from_secs(secs);
            let past_ts = now.saturating_sub(secs);
            let future_ts = now.saturating_add(secs);

            assert_eq!(past_ts.to_relative_string(now), past);
            assert_eq!(future_ts.to_relative_string(now), future);
        }
    }
}