Skip to main content

qubit_clock/sleep/
system_sleeper.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 *    SPDX-License-Identifier: Apache-2.0
6 *
7 *    Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10use std::thread;
11use std::time::Duration;
12
13use crate::sleep::Sleeper;
14#[cfg(feature = "tokio")]
15use crate::sleep::{
16    AsyncSleepFuture,
17    AsyncSleeper,
18};
19
20/// A real elapsed-time sleeper.
21///
22/// This type implements [`Sleeper`] using [`std::thread::sleep`]. When the
23/// `tokio` feature is enabled, it also implements `AsyncSleeper` using
24/// Tokio timers.
25#[derive(Clone, Copy, Debug, Default)]
26pub struct SystemSleeper;
27
28impl SystemSleeper {
29    /// Creates a new system sleeper.
30    ///
31    /// # Returns
32    ///
33    /// A sleeper that waits using real elapsed time.
34    #[inline]
35    pub const fn new() -> Self {
36        Self
37    }
38}
39
40impl Sleeper for SystemSleeper {
41    /// Blocks the current thread using [`std::thread::sleep`].
42    fn sleep_for(&self, duration: Duration) {
43        thread::sleep(duration);
44    }
45}
46
47#[cfg(feature = "tokio")]
48impl AsyncSleeper for SystemSleeper {
49    /// Returns a Tokio sleep future for the requested duration.
50    fn async_sleep_for<'a>(&'a self, duration: Duration) -> AsyncSleepFuture<'a> {
51        Box::pin(tokio::time::sleep(duration))
52    }
53}