use std::time::Duration;
use crate::sleep::Sleeper;
#[cfg(feature = "tokio")]
use crate::sleep::{
AsyncSleepFuture,
AsyncSleeper,
};
use crate::{
MockTimeline,
MockWaiterKind,
};
#[derive(Clone, Debug)]
pub struct MockSleeper {
timeline: MockTimeline,
}
impl MockSleeper {
#[must_use]
pub fn new() -> Self {
Self::with_timeline(MockTimeline::new())
}
#[must_use]
pub fn with_timeline(timeline: MockTimeline) -> Self {
Self { timeline }
}
#[inline]
pub fn timeline(&self) -> MockTimeline {
self.timeline.clone()
}
}
impl Default for MockSleeper {
fn default() -> Self {
Self::new()
}
}
impl Sleeper for MockSleeper {
fn sleep_for(&self, duration: Duration) {
let deadline = self.timeline.now().saturating_add(duration);
self.timeline
.wait_until_with_kind(deadline, MockWaiterKind::Sleep)
.expect("mock sleeper deadlines should belong to the sleeper timeline");
}
}
#[cfg(feature = "tokio")]
impl AsyncSleeper for MockSleeper {
fn sleep_for_async<'a>(&'a self, duration: Duration) -> AsyncSleepFuture<'a> {
let deadline = self.timeline.now().saturating_add(duration);
self.timeline
.wait_until_async_with_kind(deadline, MockWaiterKind::Sleep)
.expect("mock sleeper deadlines should belong to the sleeper timeline")
}
}