Skip to main content

futures_bounded/
futures_set.rs

1use std::{
2    pin::Pin,
3    task::{ready, Context, Poll},
4};
5
6use crate::{AnyFuture, BoxFuture, Delay, FuturesMap, PushError, Timeout};
7
8/// Represents a list of [Future]s.
9///
10/// Each future must finish within the specified time and the list never outgrows its capacity.
11pub struct FuturesSet<O> {
12    id: u32,
13    inner: FuturesMap<u32, O>,
14}
15
16impl<O> FuturesSet<O> {
17    pub fn new(make_delay: impl Fn() -> Delay + Send + Sync + 'static, capacity: usize) -> Self {
18        Self {
19            id: 0,
20            inner: FuturesMap::new(make_delay, capacity),
21        }
22    }
23}
24
25impl<O> FuturesSet<O>
26where
27    O: 'static,
28{
29    /// Push a future into the list.
30    ///
31    /// This method adds the given future to the list.
32    /// If the length of the list is equal to the capacity, this method returns a error that contains the passed future.
33    /// In that case, the future is not added to the set.
34    pub fn try_push<F>(&mut self, future: F) -> Result<(), BoxFuture<O>>
35    where
36        F: AnyFuture<Output = O>,
37    {
38        self.id = self.id.wrapping_add(1);
39
40        match self.inner.try_push(self.id, future) {
41            Ok(()) => Ok(()),
42            Err(PushError::BeyondCapacity(w)) => Err(w),
43            Err(PushError::Replaced(_)) => unreachable!("we never reuse IDs"),
44        }
45    }
46
47    pub fn len(&self) -> usize {
48        self.inner.len()
49    }
50
51    pub fn is_empty(&self) -> bool {
52        self.inner.is_empty()
53    }
54
55    pub fn poll_ready_unpin(&mut self, cx: &mut Context<'_>) -> Poll<()> {
56        self.inner.poll_ready_unpin(cx)
57    }
58
59    pub fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Result<O, Timeout>> {
60        let (_, res) = ready!(self.inner.poll_unpin(cx));
61
62        Poll::Ready(res)
63    }
64
65    /// Returns an iterator over all futures of type `T` pushed via [`FuturesSet::try_push`].
66    /// This iterator returns futures in an arbitrary order, which may change.
67    ///
68    /// If downcasting a future to `T` fails it will be skipped in the iterator.
69    pub fn iter_of_type<T>(&self) -> impl Iterator<Item = Pin<&T>>
70    where
71        T: 'static,
72    {
73        self.inner.iter_of_type().map(|(_, item)| item)
74    }
75
76    /// Returns an iterator with mutable access over all futures of type `T`
77    /// pushed via [`FuturesSet::try_push`].
78    /// This iterator returns futures in an arbitrary order, which may change.
79    ///
80    /// If downcasting a future to `T` fails it will be skipped in the iterator.
81    pub fn iter_mut_of_type<T>(&mut self) -> impl Iterator<Item = Pin<&mut T>>
82    where
83        T: 'static,
84    {
85        self.inner.iter_mut_of_type().map(|(_, item)| item)
86    }
87}