use std::future::Future;
use std::task::{ready, Context, Poll};
use std::time::Duration;
use futures_util::future::BoxFuture;
use crate::{FuturesMap, PushError, Timeout};
pub struct FuturesSet<O> {
id: u32,
inner: FuturesMap<u32, O>,
}
impl<O> FuturesSet<O> {
pub fn new(timeout: Duration, capacity: usize) -> Self {
Self {
id: 0,
inner: FuturesMap::new(timeout, capacity),
}
}
}
impl<O> FuturesSet<O> {
pub fn try_push<F>(&mut self, future: F) -> Result<(), BoxFuture<O>>
where
F: Future<Output = O> + Send + 'static,
{
self.id = self.id.wrapping_add(1);
match self.inner.try_push(self.id, future) {
Ok(()) => Ok(()),
Err(PushError::BeyondCapacity(w)) => Err(w),
Err(PushError::ReplacedFuture(_)) => unreachable!("we never reuse IDs"),
}
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn poll_ready_unpin(&mut self, cx: &mut Context<'_>) -> Poll<()> {
self.inner.poll_ready_unpin(cx)
}
pub fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<O, Timeout>> {
let (_, res) = ready!(self.inner.poll_unpin(cx));
Poll::Ready(res)
}
}