omaha_client/async_generator.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 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
// Copyright 2020 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
#![deny(missing_docs)]
#![allow(clippy::let_unit_value)]
//! Asynchronous generator-like functionality in stable Rust.
use {
futures::{
channel::mpsc,
future::FusedFuture,
prelude::*,
stream::FusedStream,
task::{Context, Poll},
},
pin_project::pin_project,
std::pin::Pin,
};
/// Produces an asynchronous `Stream` of [`GeneratorState<I, R>`] by invoking the given closure
/// with a handle that can be used to yield items.
///
/// The returned `Stream` will produce a GeneratorState::Yielded variant for all yielded items
/// from the asynchronous task, followed by a single GeneratorState::Complete variant, which will
/// always be present as the final element in the stream.
pub fn generate<'a, I, R, C, F>(cb: C) -> Generator<F, I, R>
where
C: FnOnce(Yield<I>) -> F,
F: Future<Output = R> + 'a,
I: Send + 'static,
R: Send + 'static,
{
let (send, recv) = mpsc::channel(0);
Generator {
task: cb(Yield(send)).fuse(),
stream: recv,
res: None,
}
}
/// Control handle to yield items to the coroutine.
pub struct Yield<I>(mpsc::Sender<I>);
impl<I> Yield<I>
where
I: Send + 'static,
{
/// Yield a single item to the coroutine, waiting for it to receive the item.
pub fn yield_(&mut self, item: I) -> impl Future<Output = ()> + '_ {
// Ignore errors as Generator never drops the stream before the task.
self.0.send(item).map(|_| ())
}
/// Yield multiple items to the coroutine, waiting for it to receive all of them.
pub fn yield_all<S>(&mut self, items: S) -> impl Future<Output = ()> + '_
where
S: IntoIterator<Item = I>,
S::IntoIter: 'static,
{
let mut items = futures::stream::iter(items.into_iter().map(Ok));
async move {
let _ = self.0.send_all(&mut items).await;
}
}
}
/// Emitted state from an async generator.
#[derive(Debug, PartialEq, Eq)]
pub enum GeneratorState<I, R> {
/// The async generator yielded a value.
Yielded(I),
/// The async generator completed with a return value.
Complete(R),
}
impl<I, R> GeneratorState<I, R> {
fn into_yielded(self) -> Option<I> {
match self {
GeneratorState::Yielded(item) => Some(item),
_ => None,
}
}
fn into_complete(self) -> Option<R> {
match self {
GeneratorState::Complete(res) => Some(res),
_ => None,
}
}
}
/// An asynchronous generator.
#[pin_project]
#[derive(Debug)]
pub struct Generator<F, I, R>
where
F: Future<Output = R>,
{
#[pin]
task: future::Fuse<F>,
#[pin]
stream: mpsc::Receiver<I>,
res: Option<R>,
}
impl<F, I, E> Generator<F, I, Result<(), E>>
where
F: Future<Output = Result<(), E>>,
{
/// Transforms this stream of `GeneratorState<I, Result<(), E>>` into a stream of `Result<I, E>`.
pub fn into_try_stream(self) -> impl FusedStream<Item = Result<I, E>> {
self.filter_map(|state| {
future::ready(match state {
GeneratorState::Yielded(i) => Some(Ok(i)),
GeneratorState::Complete(Ok(())) => None,
GeneratorState::Complete(Err(e)) => Some(Err(e)),
})
})
}
}
impl<F, I, R> Generator<F, I, R>
where
F: Future<Output = R>,
{
/// Discards all intermediate values produced by this generator, producing just the final result.
pub async fn into_complete(self) -> R {
let s = self.filter_map(|state| future::ready(state.into_complete()));
futures::pin_mut!(s);
// Generators always yield a complete item as the final element once the task
// completes.
s.next().await.unwrap()
}
}
impl<F, I> Generator<F, I, ()>
where
F: Future<Output = ()>,
{
/// Filters the states produced by this generator to only include intermediate yielded values,
/// discarding the final result.
pub fn into_yielded(self) -> impl FusedStream<Item = I> {
self.filter_map(|state| future::ready(state.into_yielded()))
}
}
impl<F, I, R> Stream for Generator<F, I, R>
where
F: Future<Output = R>,
{
type Item = GeneratorState<I, R>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.project();
// Always poll the task first to make forward progress and maybe push an item into the
// channel.
let mut task_done = this.task.is_terminated();
if let Poll::Ready(res) = this.task.poll(cx) {
// This stream might not be ready for the final result yet, store it for later.
this.res.replace(res);
task_done = true;
}
// Return anything available from the stream, ignoring stream termination to let the task
// termination yield the last value.
if !this.stream.is_terminated() {
match this.stream.poll_next(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Some(item)) => return Poll::Ready(Some(GeneratorState::Yielded(item))),
Poll::Ready(None) => {}
}
}
if !task_done {
return Poll::Pending;
}
// Flush the final result once all tasks are done.
match this.res.take() {
Some(res) => Poll::Ready(Some(GeneratorState::Complete(res))),
None => Poll::Ready(None),
}
}
}
impl<F, I, R> FusedStream for Generator<F, I, R>
where
F: Future<Output = R>,
{
fn is_terminated(&self) -> bool {
self.task.is_terminated() && self.stream.is_terminated() && self.res.is_none()
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::executor::block_on;
use std::sync::atomic;
/// Returns a future that yields to the executor once before completing.
fn yield_once() -> impl Future<Output = ()> {
let mut done = false;
future::poll_fn(move |cx: &mut Context<'_>| {
if !done {
done = true;
cx.waker().wake_by_ref();
Poll::Pending
} else {
Poll::Ready(())
}
})
}
#[derive(Debug, Default)]
struct Counter(atomic::AtomicU32);
impl Counter {
fn inc(&self) {
self.0.fetch_add(1, atomic::Ordering::SeqCst);
}
fn take(&self) -> u32 {
self.0.swap(0, atomic::Ordering::SeqCst)
}
}
#[test]
fn generator_waits_for_item_to_yield() {
let counter = Counter::default();
let s = generate(|mut co| {
let counter = &counter;
async move {
counter.inc();
co.yield_("first").await;
// This yield should not be observable by the stream, but the extra increment will
// be.
counter.inc();
yield_once().await;
counter.inc();
co.yield_("second").await;
drop(co);
yield_once().await;
counter.inc();
}
});
block_on(async {
futures::pin_mut!(s);
assert_eq!(counter.take(), 0);
assert_eq!(s.next().await, Some(GeneratorState::Yielded("first")));
assert_eq!(counter.take(), 1);
assert_eq!(s.next().await, Some(GeneratorState::Yielded("second")));
assert_eq!(counter.take(), 2);
assert_eq!(s.next().await, Some(GeneratorState::Complete(())));
assert_eq!(counter.take(), 1);
assert_eq!(s.next().await, None);
assert_eq!(counter.take(), 0);
});
}
#[test]
fn yield_all_yields_all() {
let s = generate(|mut co| async move {
co.yield_all(1u32..4).await;
co.yield_(42).await;
});
let res = block_on(s.collect::<Vec<GeneratorState<u32, ()>>>());
assert_eq!(
res,
vec![
GeneratorState::Yielded(1),
GeneratorState::Yielded(2),
GeneratorState::Yielded(3),
GeneratorState::Yielded(42),
GeneratorState::Complete(()),
]
);
}
#[test]
fn fused_impl() {
let s = generate(|mut co| async move {
co.yield_(1u32).await;
drop(co);
yield_once().await;
"done"
});
block_on(async {
futures::pin_mut!(s);
assert!(!s.is_terminated());
assert_eq!(s.next().await, Some(GeneratorState::Yielded(1)));
assert!(!s.is_terminated());
assert_eq!(s.next().await, Some(GeneratorState::Complete("done")));
// FusedStream's is_terminated typically returns false after yielding None to indicate
// no items are left, but it is also valid to return true when the stream is going to
// not make further progress.
assert!(s.is_terminated());
assert_eq!(s.next().await, None);
assert!(s.is_terminated());
});
}
#[test]
fn into_try_stream_transposes_generator_states() {
let s = generate(|mut co| async move {
co.yield_(1u8).await;
co.yield_(2u8).await;
Result::<(), &'static str>::Err("oops")
})
.into_try_stream();
let res = block_on(s.collect::<Vec<Result<u8, &'static str>>>());
assert_eq!(res, vec![Ok(1), Ok(2), Err("oops")]);
}
#[test]
fn into_try_stream_eats_unit_success() {
let s = generate(|mut co| async move {
co.yield_(1u8).await;
co.yield_(2u8).await;
Result::<(), &'static str>::Ok(())
})
.into_try_stream();
let res = block_on(s.collect::<Vec<Result<u8, &'static str>>>());
assert_eq!(res, vec![Ok(1), Ok(2)]);
}
#[test]
fn runs_task_to_completion() {
let finished = Counter::default();
let make_s = || {
generate(|mut co| async {
co.yield_(8u8).await;
// Try really hard to cause this task to be dropped without completing.
drop(co);
yield_once().await;
finished.inc();
})
};
// No matter which combinator is used.
block_on(async {
let res = make_s().collect::<Vec<GeneratorState<u8, ()>>>().await;
assert_eq!(
res,
vec![GeneratorState::Yielded(8), GeneratorState::Complete(())]
);
assert_eq!(finished.take(), 1);
});
block_on(async {
assert_eq!(make_s().into_yielded().collect::<Vec<_>>().await, vec![8]);
assert_eq!(finished.take(), 1);
});
block_on(async {
let () = make_s().into_complete().await;
assert_eq!(finished.take(), 1);
});
}
#[test]
fn fibonacci() {
let fib = generate(|mut co| async move {
let (mut a, mut b) = (0u32, 1u32);
loop {
co.yield_(a).await;
let n = b;
b += a;
a = n;
}
})
.into_yielded()
.take(10)
.collect::<Vec<_>>();
assert_eq!(block_on(fib), vec![0, 1, 1, 2, 3, 5, 8, 13, 21, 34]);
}
}