diem_time_service/
real.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use crate::TimeServiceTrait;
9#[cfg(any(test, feature = "async"))]
10use crate::{Sleep, SleepTrait};
11#[cfg(any(test, feature = "async"))]
12use std::pin::Pin;
13use std::{
14    thread,
15    time::{Duration, Instant},
16};
17
18/// The real production tokio [`TimeService`](crate::TimeService).
19///
20/// Note: `RealTimeService` is just a zero-sized type whose methods only
21/// delegate to the respective `tokio::time` functions.
22#[derive(Copy, Clone, Debug, Default)]
23pub struct RealTimeService;
24
25#[cfg(any(test, feature = "async"))]
26pub type RealSleep = tokio::time::Sleep;
27
28impl RealTimeService {
29    pub fn new() -> Self { Self {} }
30}
31
32impl TimeServiceTrait for RealTimeService {
33    fn now(&self) -> Instant { Instant::now() }
34
35    fn now_unix_time(&self) -> Duration {
36        diem_infallible::duration_since_epoch()
37    }
38
39    #[cfg(any(test, feature = "async"))]
40    fn sleep(&self, duration: Duration) -> Sleep {
41        tokio::time::sleep(duration).into()
42    }
43
44    fn sleep_blocking(&self, duration: Duration) { thread::sleep(duration); }
45}
46
47#[cfg(any(test, feature = "async"))]
48impl SleepTrait for RealSleep {
49    fn is_elapsed(&self) -> bool { RealSleep::is_elapsed(self) }
50
51    fn reset(self: Pin<&mut Self>, duration: Duration) {
52        let deadline = self.deadline() + duration;
53        RealSleep::reset(self, deadline);
54    }
55
56    fn reset_until(self: Pin<&mut Self>, deadline: Instant) {
57        RealSleep::reset(self, tokio::time::Instant::from_std(deadline));
58    }
59}