adaptive_timeout/clock.rs
1use std::time::Duration;
2
3/// An instant in time, used for measuring elapsed durations.
4///
5/// This trait abstracts over the time source so that users can provide their
6/// own clock implementations (e.g., for simulated time in tests, or for
7/// integration with async runtimes that provide their own `Instant` type).
8///
9/// The crate never calls "now" internally — callers always pass a timestamp
10/// into every method. This trait only needs to support computing the elapsed
11/// time between two instants and advancing an instant by a duration.
12///
13/// # Built-in implementation
14///
15/// [`std::time::Instant`] implements this trait, so the crate works out of
16/// the box with the standard library clock. A type alias
17/// [`LatencyTracker`](crate::LatencyTracker) defaults the clock parameter to
18/// `Instant` for ergonomic use.
19///
20/// # Example: custom clock
21///
22/// ```rust
23/// use std::time::Duration;
24/// use adaptive_timeout::Instant;
25///
26/// #[derive(Clone, Copy)]
27/// struct FakeInstant(u64); // nanoseconds
28///
29/// impl Instant for FakeInstant {
30/// fn duration_since(&self, earlier: Self) -> Duration {
31/// Duration::from_nanos(self.0.saturating_sub(earlier.0))
32/// }
33/// fn add_duration(&self, duration: Duration) -> Self {
34/// FakeInstant(self.0 + duration.as_nanos() as u64)
35/// }
36/// }
37/// ```
38pub trait Instant: Copy + Clone {
39 /// Returns the duration elapsed from `earlier` to `self`.
40 ///
41 /// Equivalent to `self - earlier` for `std::time::Instant`. If `self` is
42 /// before `earlier` (clock skew), the implementation should return
43 /// `Duration::ZERO` rather than panicking.
44 fn duration_since(&self, earlier: Self) -> Duration;
45
46 /// Returns a new instant that is `duration` later than `self`.
47 ///
48 /// Equivalent to `self + duration` for `std::time::Instant`.
49 fn add_duration(&self, duration: Duration) -> Self;
50}
51
52impl Instant for std::time::Instant {
53 #[inline]
54 fn duration_since(&self, earlier: Self) -> Duration {
55 std::time::Instant::duration_since(self, earlier)
56 }
57
58 #[inline]
59 fn add_duration(&self, duration: Duration) -> Self {
60 *self + duration
61 }
62}
63
64#[cfg(feature = "tokio")]
65impl Instant for tokio::time::Instant {
66 fn duration_since(&self, earlier: Self) -> Duration {
67 tokio::time::Instant::duration_since(self, earlier)
68 }
69
70 fn add_duration(&self, duration: Duration) -> Self {
71 *self + duration
72 }
73}