s2n_quic_core/time/clock/
std.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use super::*;
5use ::std::time::Instant;
6
7impl<C: 'static + Clock> Clock for &'static ::std::thread::LocalKey<C> {
8    fn get_time(&self) -> Timestamp {
9        self.with(|clock| clock.get_time())
10    }
11}
12
13#[derive(Clone, Copy, Debug)]
14pub struct StdClock {
15    epoch: Instant,
16}
17
18impl Default for StdClock {
19    fn default() -> Self {
20        Self {
21            epoch: Instant::now(),
22        }
23    }
24}
25
26impl StdClock {
27    /// Creates a new `StdClock` with the given epoch
28    pub const fn new(epoch: Instant) -> Self {
29        Self { epoch }
30    }
31}
32
33impl Clock for StdClock {
34    fn get_time(&self) -> Timestamp {
35        unsafe { Timestamp::from_duration(self.epoch.elapsed()) }
36    }
37}
38
39#[test]
40#[cfg_attr(miri, ignore)] // time isn't queryable in miri
41fn monotonicity_test() {
42    let clock = StdClock::default();
43    let ts1 = clock.get_time();
44    ::std::thread::sleep(Duration::from_millis(50));
45    let ts2 = clock.get_time();
46    assert!(ts2 - ts1 >= Duration::from_millis(50));
47}