-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathfuture.rs
More file actions
233 lines (211 loc) · 6.83 KB
/
future.rs
File metadata and controls
233 lines (211 loc) · 6.83 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
//! Asynchronous values.
//!
//! # Cancellation
//!
//! Futures can be cancelled by dropping them before they finish executing. This
//! is useful when we're no longer interested in the result of an operation, as
//! it allows us to stop doing needless work. This also means that a future may cancel at any `.await` point, and so just
//! like with `?` we have to be careful to roll back local state if our future
//! halts there.
//!
//!
//! ```no_run
//! use futures_lite::prelude::*;
//! use wstd::prelude::*;
//! use wstd::time::Duration;
//!
//! #[wstd::main]
//! async fn main() {
//! let mut counter = 0;
//! let value = async { "meow" }
//! .delay(Duration::from_millis(100))
//! .timeout(Duration::from_millis(200))
//! .await;
//!
//! assert_eq!(value.unwrap(), "meow");
//! }
//! ```
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
use pin_project_lite::pin_project;
use crate::time::utils::timeout_err;
pub use self::future_ext::FutureExt;
// ---- Delay ----
pin_project! {
/// Suspends a future until the specified deadline.
///
/// This `struct` is created by the [`delay`] method on [`FutureExt`]. See its
/// documentation for more.
///
/// [`delay`]: crate::future::FutureExt::delay
/// [`FutureExt`]: crate::future::futureExt
#[must_use = "futures do nothing unless polled or .awaited"]
pub struct Delay<F, D> {
#[pin]
future: F,
#[pin]
deadline: D,
state: State,
}
}
/// The internal state
#[derive(Debug)]
enum State {
Started,
PollFuture,
Completed,
}
impl<F, D> Delay<F, D> {
fn new(future: F, deadline: D) -> Self {
Self {
future,
deadline,
state: State::Started,
}
}
}
impl<F: Future, D: Future> Future for Delay<F, D> {
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
loop {
match this.state {
State::Started => {
ready!(this.deadline.as_mut().poll(cx));
*this.state = State::PollFuture;
}
State::PollFuture => {
let value = ready!(this.future.as_mut().poll(cx));
*this.state = State::Completed;
return Poll::Ready(value);
}
State::Completed => panic!("future polled after completing"),
}
}
}
}
// ---- Timeout ----
pin_project! {
/// A future that times out after a duration of time.
///
/// This `struct` is created by the [`timeout`] method on [`FutureExt`]. See its
/// documentation for more.
///
/// [`timeout`]: crate::future::FutureExt::timeout
/// [`FutureExt`]: crate::future::futureExt
#[must_use = "futures do nothing unless polled or .awaited"]
pub struct Timeout<F, D> {
#[pin]
future: F,
#[pin]
deadline: D,
completed: bool,
}
}
impl<F, D> Timeout<F, D> {
fn new(future: F, deadline: D) -> Self {
Self {
future,
deadline,
completed: false,
}
}
}
impl<F: Future, D: Future> Future for Timeout<F, D> {
type Output = io::Result<F::Output>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
assert!(!*this.completed, "future polled after completing");
match this.future.poll(cx) {
Poll::Ready(v) => {
*this.completed = true;
Poll::Ready(Ok(v))
}
Poll::Pending => match this.deadline.poll(cx) {
Poll::Ready(_) => {
*this.completed = true;
Poll::Ready(Err(timeout_err("future timed out")))
}
Poll::Pending => Poll::Pending,
},
}
}
}
// ---- FutureExt ----
mod future_ext {
use super::{Delay, Timeout};
use std::future::{Future, IntoFuture};
/// Extend `Future` with time-based operations.
pub trait FutureExt: Future {
/// Return an error if a future does not complete within a given time span.
///
/// Typically timeouts are, as the name implies, based on _time_. However
/// this method can time out based on any future. This can be useful in
/// combination with channels, as it allows (long-lived) futures to be
/// cancelled based on some external event.
///
/// When a timeout is returned, the future will be dropped and destructors
/// will be run.
///
/// # Example
///
/// ```no_run
/// use wstd::prelude::*;
/// use wstd::time::{Instant, Duration};
/// use std::io;
///
/// #[wstd::main]
/// async fn main() {
/// let res = async { "meow" }
/// .delay(Duration::from_millis(100)) // longer delay
/// .timeout(Duration::from_millis(50)) // shorter timeout
/// .await;
/// assert_eq!(res.unwrap_err().kind(), io::ErrorKind::TimedOut); // error
///
/// let res = async { "meow" }
/// .delay(Duration::from_millis(50)) // shorter delay
/// .timeout(Duration::from_millis(100)) // longer timeout
/// .await;
/// assert_eq!(res.unwrap(), "meow"); // success
/// }
/// ```
fn timeout<D>(self, deadline: D) -> Timeout<Self, D::IntoFuture>
where
Self: Sized,
D: IntoFuture,
{
Timeout::new(self, deadline.into_future())
}
/// Delay resolving the future until the given deadline.
///
/// The underlying future will not be polled until the deadline has expired. In addition
/// to using a time source as a deadline, any future can be used as a
/// deadline too. When used in combination with a multi-consumer channel,
/// this method can be used to synchronize the start of multiple futures and streams.
///
/// # Example
///
/// ```no_run
/// use wstd::prelude::*;
/// use wstd::time::{Instant, Duration};
///
/// #[wstd::main]
/// async fn main() {
/// let now = Instant::now();
/// let delay = Duration::from_millis(100);
/// let _ = async { "meow" }.delay(delay).await;
/// assert!(now.elapsed() >= delay);
/// }
/// ```
fn delay<D>(self, deadline: D) -> Delay<Self, D::IntoFuture>
where
Self: Sized,
D: IntoFuture,
{
Delay::new(self, deadline.into_future())
}
}
impl<T> FutureExt for T where T: Future {}
}