#![cfg_attr(not(feature = "rt"), allow(dead_code))]
cfg_not_test_util! {
use crate::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub(crate) struct Clock {}
pub(crate) fn now() -> Instant {
Instant::from_std(std::time::Instant::now())
}
impl Clock {
pub(crate) fn new(_enable_pausing: bool, _start_paused: bool) -> Clock {
Clock {}
}
pub(crate) fn now(&self) -> Instant {
now()
}
pub(crate) fn is_paused(&self) -> bool {
false
}
pub(crate) fn advance(&self, _dur: Duration) {
unreachable!();
}
}
}
cfg_test_util! {
use crate::time::{Duration, Instant};
use std::sync::{Arc, Mutex};
cfg_rt! {
fn clock() -> Option<Clock> {
crate::runtime::context::clock()
}
}
cfg_not_rt! {
fn clock() -> Option<Clock> {
None
}
}
#[derive(Debug, Clone)]
pub(crate) struct Clock {
inner: Arc<Mutex<Inner>>,
}
#[derive(Debug)]
struct Inner {
enable_pausing: bool,
base: std::time::Instant,
unfrozen: Option<std::time::Instant>,
}
pub fn pause() {
let clock = clock().expect("time cannot be frozen from outside the Tokio runtime");
clock.pause();
}
pub fn resume() {
let clock = clock().expect("time cannot be frozen from outside the Tokio runtime");
let mut inner = clock.inner.lock().unwrap();
if inner.unfrozen.is_some() {
panic!("time is not frozen");
}
inner.unfrozen = Some(std::time::Instant::now());
}
pub async fn advance(duration: Duration) {
use crate::future::poll_fn;
use std::task::Poll;
let clock = clock().expect("time cannot be frozen from outside the Tokio runtime");
clock.advance(duration);
let mut yielded = false;
poll_fn(|cx| {
if yielded {
Poll::Ready(())
} else {
yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}).await;
}
pub(crate) fn now() -> Instant {
if let Some(clock) = clock() {
clock.now()
} else {
Instant::from_std(std::time::Instant::now())
}
}
impl Clock {
pub(crate) fn new(enable_pausing: bool, start_paused: bool) -> Clock {
let now = std::time::Instant::now();
let clock = Clock {
inner: Arc::new(Mutex::new(Inner {
enable_pausing,
base: now,
unfrozen: Some(now),
})),
};
if start_paused {
clock.pause();
}
clock
}
pub(crate) fn pause(&self) {
let mut inner = self.inner.lock().unwrap();
if !inner.enable_pausing {
drop(inner); panic!("`time::pause()` requires the `current_thread` Tokio runtime. \
This is the default Runtime used by `#[tokio::test].");
}
let elapsed = inner.unfrozen.as_ref().expect("time is already frozen").elapsed();
inner.base += elapsed;
inner.unfrozen = None;
}
pub(crate) fn is_paused(&self) -> bool {
let inner = self.inner.lock().unwrap();
inner.unfrozen.is_none()
}
pub(crate) fn advance(&self, duration: Duration) {
let mut inner = self.inner.lock().unwrap();
if inner.unfrozen.is_some() {
panic!("time is not frozen");
}
inner.base += duration;
}
pub(crate) fn now(&self) -> Instant {
let inner = self.inner.lock().unwrap();
let mut ret = inner.base;
if let Some(unfrozen) = inner.unfrozen {
ret += unfrozen.elapsed();
}
Instant::from_std(ret)
}
}
}