Skip to content

Commit 108a74f

Browse files
committed
feat(s2n-quic-core): add Cached clock implementation
1 parent 311ece3 commit 108a74f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

quic/s2n-quic-core/src/time/clock.rs

+36
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,39 @@ impl Clock for NoopClock {
4848
unsafe { Timestamp::from_duration(Duration::from_micros(1)) }
4949
}
5050
}
51+
52+
impl Clock for Timestamp {
53+
#[inline]
54+
fn get_time(&self) -> Timestamp {
55+
*self
56+
}
57+
}
58+
59+
/// A clock that caches the time query for the inner clock
60+
pub struct Cached<'a, C: Clock> {
61+
clock: &'a C,
62+
cached_value: core::cell::Cell<Option<Timestamp>>,
63+
}
64+
65+
impl<'a, C: Clock> Cached<'a, C> {
66+
#[inline]
67+
pub fn new(clock: &'a C) -> Self {
68+
Self {
69+
clock,
70+
cached_value: Default::default(),
71+
}
72+
}
73+
}
74+
75+
impl<'a, C: Clock> Clock for Cached<'a, C> {
76+
#[inline]
77+
fn get_time(&self) -> Timestamp {
78+
if let Some(time) = self.cached_value.get() {
79+
return time;
80+
}
81+
82+
let now = self.clock.get_time();
83+
self.cached_value.set(Some(now));
84+
now
85+
}
86+
}

0 commit comments

Comments
 (0)