use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};
use crate::timer::{BoxFuture, Refused, Timer};
#[derive(Clone)]
pub struct ScriptedTimer(Arc<Mutex<Script>>);
struct Script {
base: Instant,
at: Duration,
live: HashMap<Duration, usize>,
pending_at: HashMap<Duration, Duration>,
refusing: HashMap<Duration, usize>,
waiting: Vec<Waker>,
}
struct Sleep {
clock: ScriptedTimer,
length: Duration,
until: Duration,
}
impl ScriptedTimer {
pub fn new() -> ScriptedTimer {
ScriptedTimer(Arc::new(Mutex::new(Script { base: Instant::now(), at: Duration::ZERO, live: HashMap::new(), pending_at: HashMap::new(), refusing: HashMap::new(), waiting: Vec::new() })))
}
pub fn advance(&self, by: Duration) {
let waiting = {
let mut script = self.lock();
script.at += by;
std::mem::take(&mut script.waiting)
};
waiting.into_iter().for_each(Waker::wake);
}
pub fn live(&self, length: Duration) -> usize {
self.lock().live.get(&length).copied().unwrap_or(0)
}
pub fn pending_at(&self, length: Duration) -> Option<Duration> {
self.lock().pending_at.get(&length).copied()
}
pub fn refuse(&self, length: Duration) {
self.lock().refusing.entry(length).or_default();
}
pub fn refused(&self, length: Duration) -> usize {
self.lock().refusing.get(&length).copied().unwrap_or(0)
}
fn refusing(&self, length: Duration) -> bool {
match self.lock().refusing.get_mut(&length) {
Some(asked) => {
*asked += 1;
true
}
None => false,
}
}
pub fn elapsed(&self) -> Duration {
self.lock().at
}
fn lock(&self) -> std::sync::MutexGuard<'_, Script> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Default for ScriptedTimer {
fn default() -> Self {
ScriptedTimer::new()
}
}
impl Timer for ScriptedTimer {
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()> {
if self.refusing(d) {
return Box::pin(std::future::ready(()));
}
let until = {
let mut script = self.lock();
*script.live.entry(d).or_default() += 1;
script.at + d
};
Box::pin(Sleep { clock: self.clone(), length: d, until })
}
fn now(&self) -> Instant {
let script = self.lock();
script.base + script.at
}
fn try_sleep(&self, d: Duration) -> BoxFuture<'static, Result<(), Refused>> {
if self.refusing(d) {
return Box::pin(std::future::ready(Err(Refused)));
}
let sleep = Timer::sleep(self, d);
Box::pin(async move {
sleep.await;
Ok(())
})
}
}
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let mut script = self.clock.lock();
if script.at >= self.until {
return Poll::Ready(());
}
let at = script.at;
script.pending_at.insert(self.length, at);
script.waiting.push(cx.waker().clone());
Poll::Pending
}
}
impl Drop for Sleep {
fn drop(&mut self) {
if let Some(live) = self.clock.lock().live.get_mut(&self.length) {
*live -= 1;
}
}
}