use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use futures::channel::oneshot;
use crate::actor::Actor;
use crate::clock::{interval_at, Delay, Instant, Interval};
use crate::fut::{ActorFuture, ActorStream};
pub struct Condition<T>
where
T: Clone,
{
waiters: Vec<oneshot::Sender<T>>,
}
impl<T> Condition<T>
where
T: Clone,
{
pub fn wait(&mut self) -> oneshot::Receiver<T> {
let (tx, rx) = oneshot::channel();
self.waiters.push(tx);
rx
}
pub fn set(self, result: T) {
for waiter in self.waiters {
let _ = waiter.send(result.clone());
}
}
}
impl<T> Default for Condition<T>
where
T: Clone,
{
fn default() -> Self {
Condition {
waiters: Vec::new(),
}
}
}
#[must_use = "future do nothing unless polled"]
pub struct TimerFunc<A>
where
A: Actor,
{
f: Option<Box<dyn TimerFuncBox<A>>>,
timeout: Delay,
}
impl<A> TimerFunc<A>
where
A: Actor,
{
pub fn new<F>(timeout: Duration, f: F) -> TimerFunc<A>
where
F: FnOnce(&mut A, &mut A::Context) + 'static,
{
TimerFunc {
f: Some(Box::new(f)),
timeout: tokio::time::delay_for(timeout),
}
}
}
trait TimerFuncBox<A: Actor>: 'static {
fn call(self: Box<Self>, _: &mut A, _: &mut A::Context);
}
impl<A: Actor, F: FnOnce(&mut A, &mut A::Context) + 'static> TimerFuncBox<A> for F {
#[allow(clippy::boxed_local)]
fn call(self: Box<Self>, act: &mut A, ctx: &mut A::Context) {
(*self)(act, ctx)
}
}
impl<A> ActorFuture for TimerFunc<A>
where
A: Actor,
{
type Output = ();
type Actor = A;
fn poll(
self: Pin<&mut Self>,
act: &mut Self::Actor,
ctx: &mut <Self::Actor as Actor>::Context,
task: &mut Context<'_>,
) -> Poll<Self::Output> {
let this = self.get_mut();
match Pin::new(&mut this.timeout).poll(task) {
Poll::Ready(_) => {
if let Some(f) = this.f.take() {
f.call(act, ctx);
}
Poll::Ready(())
}
Poll::Pending => Poll::Pending,
}
}
}
#[must_use = "future do nothing unless polled"]
pub struct IntervalFunc<A: Actor> {
f: Box<dyn IntervalFuncBox<A>>,
interval: Interval,
}
impl<A: Actor> IntervalFunc<A> {
pub fn new<F>(timeout: Duration, f: F) -> IntervalFunc<A>
where
F: FnMut(&mut A, &mut A::Context) + 'static,
{
Self {
f: Box::new(f),
interval: interval_at(Instant::now() + timeout, timeout),
}
}
}
trait IntervalFuncBox<A: Actor>: 'static {
fn call(&mut self, _: &mut A, _: &mut A::Context);
}
impl<A: Actor, F: FnMut(&mut A, &mut A::Context) + 'static> IntervalFuncBox<A> for F {
#[allow(clippy::boxed_local)]
fn call(&mut self, act: &mut A, ctx: &mut A::Context) {
(*self)(act, ctx)
}
}
impl<A: Actor> ActorStream for IntervalFunc<A> {
type Item = ();
type Actor = A;
fn poll_next(
self: Pin<&mut Self>,
act: &mut Self::Actor,
ctx: &mut <Self::Actor as Actor>::Context,
task: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
loop {
match this.interval.poll_tick(task) {
Poll::Ready(_) => {
this.f.call(act, ctx);
}
Poll::Pending => return Poll::Pending,
}
}
}
}