-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathvec.rs
158 lines (140 loc) · 4.23 KB
/
vec.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
use super::Join as JoinTrait;
use crate::utils::{iter_pin_mut_vec, PollState};
use core::fmt;
use core::future::{Future, IntoFuture};
use core::pin::Pin;
use core::task::{Context, Poll};
use std::mem::{self, MaybeUninit};
use std::vec::Vec;
use pin_project::{pin_project, pinned_drop};
/// Waits for two similarly-typed futures to complete.
///
/// Awaits multiple futures simultaneously, returning the output of the
/// futures once both complete.
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[pin_project(PinnedDrop)]
pub struct Join<Fut>
where
Fut: Future,
{
consumed: bool,
pending: usize,
items: Vec<MaybeUninit<<Fut as Future>::Output>>,
state: Vec<PollState>,
#[pin]
futures: Vec<Fut>,
}
impl<Fut> Join<Fut>
where
Fut: Future,
{
pub(crate) fn new(futures: Vec<Fut>) -> Self {
Join {
consumed: false,
pending: futures.len(),
items: std::iter::repeat_with(|| MaybeUninit::uninit())
.take(futures.len())
.collect(),
state: vec![PollState::default(); futures.len()],
futures,
}
}
}
impl<Fut> JoinTrait for Vec<Fut>
where
Fut: IntoFuture,
{
type Output = Vec<Fut::Output>;
type Future = Join<Fut::IntoFuture>;
fn join(self) -> Self::Future {
Join::new(self.into_iter().map(IntoFuture::into_future).collect())
}
}
impl<Fut> fmt::Debug for Join<Fut>
where
Fut: Future + fmt::Debug,
Fut::Output: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.state.iter()).finish()
}
}
impl<Fut> Future for Join<Fut>
where
Fut: Future,
{
type Output = Vec<Fut::Output>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
assert!(
!*this.consumed,
"Futures must not be polled after completing"
);
// Poll all futures
let futures = this.futures.as_mut();
for (i, fut) in iter_pin_mut_vec(futures).enumerate() {
if this.state[i].is_pending() {
if let Poll::Ready(value) = fut.poll(cx) {
this.items[i] = MaybeUninit::new(value);
this.state[i] = PollState::Done;
*this.pending -= 1;
}
}
}
// Check whether we're all done now or need to keep going.
if *this.pending == 0 {
// Mark all data as "consumed" before we take it
*this.consumed = true;
this.state.iter_mut().for_each(|state| {
debug_assert!(state.is_done(), "Future should have reached a `Done` state");
*state = PollState::Consumed;
});
// SAFETY: we've checked with the state that all of our outputs have been
// filled, which means we're ready to take the data and assume it's initialized.
let items = unsafe {
let items = mem::take(this.items);
mem::transmute::<_, Vec<Fut::Output>>(items)
};
Poll::Ready(items)
} else {
Poll::Pending
}
}
}
/// Drop the already initialized values on cancellation.
#[pinned_drop]
impl<Fut> PinnedDrop for Join<Fut>
where
Fut: Future,
{
fn drop(self: Pin<&mut Self>) {
let this = self.project();
// Get the indexes of the initialized values.
let indexes = this
.state
.iter_mut()
.enumerate()
.filter(|(_, state)| state.is_done())
.map(|(i, _)| i);
// Drop each value at the index.
for i in indexes {
// SAFETY: we've just filtered down to *only* the initialized values.
// We can assume they're initialized, and this is where we drop them.
unsafe { this.items[i].assume_init_drop() };
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::future;
#[test]
fn smoke() {
futures_lite::future::block_on(async {
let res = vec![future::ready("hello"), future::ready("world")]
.join()
.await;
assert_eq!(res, vec!["hello", "world"]);
});
}
}