Skip to main content

execution_policy/core/
tokio.rs

1use std::sync::atomic::{AtomicU64, Ordering};
2use std::time::{Duration, Instant};
3
4use super::rng::SplitMix64;
5use super::{BoxFuture, Core};
6
7/// Default production [`Core`]: tokio timers + a fast non-crypto RNG for jitter.
8#[derive(Debug)]
9pub struct TokioCore {
10    rng_state: AtomicU64,
11}
12
13impl Default for TokioCore {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl TokioCore {
20    pub fn new() -> Self {
21        // Seed from process-relative nanos; jitter quality only, not security.
22        let seed = Instant::now().elapsed().as_nanos() as u64 ^ 0x2545_F491_4F6C_DD1D;
23        Self {
24            rng_state: AtomicU64::new(seed.max(1)),
25        }
26    }
27}
28
29impl Core for TokioCore {
30    fn now(&self) -> Instant {
31        Instant::now()
32    }
33
34    fn sleep(&self, dur: Duration) -> BoxFuture<'_, ()> {
35        Box::pin(tokio::time::sleep(dur))
36    }
37
38    fn next_u64(&self) -> u64 {
39        let s = self
40            .rng_state
41            .fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed);
42        SplitMix64::new(s).next_u64()
43    }
44}