libsw_core/
instant.rs

1// libsw: stopwatch library
2// copyright (C) 2022-2023 Ula Shipman <ula.hello@mailbox.org>
3// licensed under MIT OR Apache-2.0
4
5use ::core::fmt::Debug;
6use ::core::time::Duration;
7
8/// A trait outlining the behavior of a timekeeping type.
9///
10/// This trait allows `libsw` to be agnostic about timekeeping: any type which
11/// implements `Instant` can be used within a
12/// [`Stopwatch`](crate::Stopwatch).
13///
14/// # Provided implementations
15///
16/// `libsw_core` provides `Instant` implementations for timekeeping types in the
17/// standard library.
18///
19/// | Type                    | Feature flag | Notes       |
20/// |-------------------------|--------------|-------------|
21/// | `std::time::Instant`    | `std`        |             |
22/// | `std::time::SystemTime` | `std`        |             |
23/// | `tokio::time::Instant`  | `tokio`      |             |
24/// | `coarsetime::Instant`   | `coarsetime` |             |
25/// | `quanta::Instant`       | `quanta`     |             |
26/// | `time::Instant`         | `time`       | Deprecated. |
27///
28/// If a timekeeping type you want to use isn't supported out of the box, please
29/// consider [filing an issue](https://github.com/ulahello/libsw-core/issues)
30/// on GitHub. If you already implemented `Instant` for it, consider sending a
31/// PR upstream.
32pub trait Instant: Copy + Debug + Sized {
33    /// Returns the current instant in time.
34    fn now() -> Self;
35
36    /// Returns an instant ahead of `self` by the given [`Duration`] of time.
37    ///
38    /// Returns [`None`] if overflow occured, meaning the new instant was not
39    /// representable with the underlying type.
40    fn checked_add(&self, duration: Duration) -> Option<Self>;
41
42    /// Returns an instant previous to `self` by the given [`Duration`] of time.
43    ///
44    /// Returns [`None`] if overflow occured, meaning the new instant was not
45    /// representable with the underlying type.
46    fn checked_sub(&self, duration: Duration) -> Option<Self>;
47
48    /// Returns the [`Duration`] that has elapsed since `earlier`, returning
49    /// [`Duration::ZERO`] if `earlier` is ahead of `self`.
50    fn saturating_duration_since(&self, earlier: Self) -> Duration;
51}