futures_bounded/
futures_set.rs1use std::{
2 pin::Pin,
3 task::{ready, Context, Poll},
4};
5
6use crate::{AnyFuture, BoxFuture, Delay, FuturesMap, PushError, Timeout};
7
8pub 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 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 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 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}