pollable_map/futures/
set.rs

1use std::future::Future;
2use std::pin::Pin;
3
4use super::FutureMap;
5use futures::{Stream, StreamExt};
6use std::task::{Context, Poll};
7
8pub struct FutureSet<S> {
9    id: i64,
10    map: FutureMap<i64, S>,
11}
12
13impl<S> Default for FutureSet<S>
14where
15    S: Future + Send + Unpin + 'static,
16{
17    fn default() -> Self {
18        Self::new()
19    }
20}
21
22impl<S> FutureSet<S>
23where
24    S: Future + Send + Unpin + 'static,
25{
26    /// Creates an empty ['FutureSet`]
27    pub fn new() -> Self {
28        Self {
29            id: 0,
30            map: FutureMap::default(),
31        }
32    }
33
34    /// Insert a future into the set of futures.
35    pub fn insert(&mut self, fut: S) -> bool {
36        let id = self.id.wrapping_add(1);
37        self.map.insert(id, fut)
38    }
39
40    /// An iterator visiting all futures in arbitrary order.
41    pub fn iter(&self) -> impl Iterator<Item = &S> {
42        self.map.iter().map(|(_, st)| st)
43    }
44
45    /// An iterator visiting all futures mutably in arbitrary order.
46    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut S> {
47        self.map.iter_mut().map(|(_, st)| st)
48    }
49
50    /// An iterator visiting all futures pinned valued in arbitrary order
51    pub fn iter_pin(&mut self) -> impl Iterator<Item = Pin<&mut S>> {
52        self.map.iter_pin().map(|(_, st)| st)
53    }
54
55    /// Clears the set.
56    pub fn clear(&mut self) {
57        self.map.clear();
58    }
59
60    /// Returns the number of futures in the set.
61    pub fn len(&self) -> usize {
62        self.map.len()
63    }
64
65    /// Return `true` map contains no elements.
66    pub fn is_empty(&self) -> bool {
67        self.map.is_empty()
68    }
69}
70
71impl<S> FromIterator<S> for FutureSet<S>
72where
73    S: Future + Send + Unpin + 'static,
74{
75    fn from_iter<I: IntoIterator<Item = S>>(iter: I) -> Self {
76        let mut maps = Self::new();
77        for st in iter {
78            maps.insert(st);
79        }
80        maps
81    }
82}
83
84impl<S> Stream for FutureSet<S>
85where
86    S: Future + Send + Unpin + 'static,
87{
88    type Item = S::Output;
89
90    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
91        self.map
92            .poll_next_unpin(cx)
93            .map(|output| output.map(|(_, item)| item))
94    }
95
96    fn size_hint(&self) -> (usize, Option<usize>) {
97        self.map.size_hint()
98    }
99}