/rust/registry/src/index.crates.io-1949cf8c6b5b557f/jiff-0.2.28/src/util/cache.rs
Line | Count | Source |
1 | | use std::time::{Duration, Instant as MonotonicInstant}; |
2 | | |
3 | | /// A little helper for representing expiration time. |
4 | | /// |
5 | | /// An overflowing expiration time is treated identically to a time that is |
6 | | /// always expired. |
7 | | /// |
8 | | /// When `None` internally, it implies that the expiration time is at some |
9 | | /// arbitrary point in the past beyond all possible "time to live" values. |
10 | | /// i.e., A `None` value invalidates the cache at the next failed lookup. |
11 | | #[derive(Clone, Copy, Debug)] |
12 | | pub(crate) struct Expiration(Option<MonotonicInstant>); |
13 | | |
14 | | impl Expiration { |
15 | | /// Returns an expiration time for which `is_expired` returns true after |
16 | | /// the given duration has elapsed from this instant. |
17 | 0 | pub(crate) fn after(ttl: Duration) -> Expiration { |
18 | | Expiration( |
19 | 0 | crate::now::monotonic_time().and_then(|now| now.checked_add(ttl)), |
20 | | ) |
21 | 0 | } |
22 | | |
23 | | /// Returns an expiration time for which `is_expired` always returns true. |
24 | 0 | pub(crate) const fn expired() -> Expiration { |
25 | 0 | Expiration(None) |
26 | 0 | } |
27 | | |
28 | | /// Whether expiration has occurred or not. |
29 | 0 | pub(crate) fn is_expired(self) -> bool { |
30 | 0 | self.0.map_or(true, |t| { |
31 | 0 | let Some(now) = crate::now::monotonic_time() else { return true }; |
32 | 0 | now > t |
33 | 0 | }) |
34 | 0 | } |
35 | | } |
36 | | |
37 | | impl core::fmt::Display for Expiration { |
38 | 0 | fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { |
39 | 0 | let maybe_duration = self.0.and_then(|instant| { |
40 | 0 | crate::now::monotonic_time() |
41 | 0 | .and_then(|now| instant.checked_duration_since(now)) |
42 | 0 | }); |
43 | 0 | match maybe_duration { |
44 | 0 | None => f.write_str("expired"), |
45 | 0 | Some(duration) => core::fmt::Debug::fmt(&duration, f), |
46 | | } |
47 | 0 | } |
48 | | } |