cs_utils/utils/futures/wait.rs
1use rand::distributions::uniform::SampleRange;
2use tokio::time;
3
4use crate::random_number;
5
6/// Asynchronously wait for `ms` milliseconds.
7///
8/// ### Examples
9///
10/// ```
11/// use cs_utils::futures::wait;
12/// use tokio::time::{Instant, Duration};
13///
14/// #[tokio::main]
15/// async fn main() {
16/// let start_time = Instant::now();
17/// println!("start");
18/// wait(1000).await;
19/// println!("end");
20///
21/// assert!(
22/// (Instant::now() - start_time) >= Duration::from_millis(1000),
23/// );
24/// }
25/// ```
26pub async fn wait(ms: u64) {
27 time::sleep(time::Duration::from_millis(ms)).await;
28}
29
30/// Asynchronously wait for `micros` microseconds.
31///
32/// ### Examples
33///
34/// ```
35/// use cs_utils::futures::wait_micros;
36/// use tokio::time::{Instant, Duration};
37///
38/// #[tokio::main]
39/// async fn main() {
40/// let start_time = Instant::now();
41/// println!("start");
42/// wait_micros(1000).await;
43/// println!("end");
44///
45/// assert!(
46/// (Instant::now() - start_time) >= Duration::from_micros(1000),
47/// );
48/// }
49/// ```
50pub async fn wait_micros(micros: u64) {
51 time::sleep(time::Duration::from_micros(micros)).await;
52}
53
54/// Asynchronously wait for `nanos` nanoseconds.
55///
56/// ### Examples
57///
58/// ```
59/// use cs_utils::futures::wait_nanos;
60/// use tokio::time::{Instant, Duration};
61///
62/// #[tokio::main]
63/// async fn main() {
64/// let start_time = Instant::now();
65/// println!("start");
66/// wait_nanos(1000).await;
67/// println!("end");
68///
69/// assert!(
70/// (Instant::now() - start_time) >= Duration::from_nanos(1000),
71/// );
72/// }
73/// ```
74pub async fn wait_nanos(nanos: u64) {
75 time::sleep(time::Duration::from_nanos(nanos)).await;
76}
77
78/// Asynchronously wait for some `random number` of milliseconds.
79///
80/// ### Examples
81///
82/// ```
83/// use cs_utils::futures::wait_random;
84/// use tokio::time::{Instant, Duration};
85///
86/// #[tokio::main]
87/// async fn main() {
88/// let start_time = Instant::now();
89/// println!("start");
90/// wait_random(500..1000).await;
91/// println!("end");
92///
93/// assert!(
94/// (Instant::now() - start_time) >= Duration::from_millis(500),
95/// );
96///
97/// assert!(
98/// (Instant::now() - start_time) <= Duration::from_millis(1000 + 100),
99/// );
100/// }
101///
102/// ```
103pub async fn wait_random<T: SampleRange<u64>>(range: T) {
104 let ms = random_number(range);
105
106 time::sleep(time::Duration::from_millis(ms)).await;
107}