1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // compile-flags: --edition=2018
13 #![feature(arbitrary_self_types, async_await, await_macro, futures_api, pin)]
15 use std::boxed::PinBox;
17 use std::future::Future;
20 atomic::{self, AtomicUsize},
24 Executor, TaskObj, SpawnObjError,
25 local_waker_from_nonlocal,
32 impl Wake for Counter {
33 fn wake(this: &Arc<Self>) {
34 this.wakes.fetch_add(1, atomic::Ordering::SeqCst);
39 impl Executor for NoopExecutor {
40 fn spawn_obj(&mut self, _: TaskObj) -> Result<(), SpawnObjError> {
45 struct WakeOnceThenComplete(bool);
47 fn wake_and_yield_once() -> WakeOnceThenComplete { WakeOnceThenComplete(false) }
49 impl Future for WakeOnceThenComplete {
51 fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<()> {
62 fn async_block(x: u8) -> impl Future<Output = u8> {
64 await!(wake_and_yield_once());
69 fn async_nonmove_block(x: u8) -> impl Future<Output = u8> {
72 await!(wake_and_yield_once());
79 fn async_closure(x: u8) -> impl Future<Output = u8> {
80 (async move |x: u8| -> u8 {
81 await!(wake_and_yield_once());
86 async fn async_fn(x: u8) -> u8 {
87 await!(wake_and_yield_once());
91 async fn async_fn_with_borrow(x: &u8) -> u8 {
92 await!(wake_and_yield_once());
96 fn async_fn_with_internal_borrow(y: u8) -> impl Future<Output = u8> {
98 await!(async_fn_with_borrow(&y))
102 unsafe async fn unsafe_async_fn(x: u8) -> u8 {
103 await!(wake_and_yield_once());
108 async fn async_method(x: u8) -> u8 {
110 await!(unsafe_async_fn())
115 fn test_future_yields_once_then_returns<F, Fut>(f: F)
117 F: FnOnce(u8) -> Fut,
118 Fut: Future<Output = u8>,
120 let mut fut = PinBox::new(f(9));
121 let counter = Arc::new(Counter { wakes: AtomicUsize::new(0) });
122 let waker = local_waker_from_nonlocal(counter.clone());
123 let executor = &mut NoopExecutor;
124 let cx = &mut Context::new(&waker, executor);
126 assert_eq!(0, counter.wakes.load(atomic::Ordering::SeqCst));
127 assert_eq!(Poll::Pending, fut.as_pin_mut().poll(cx));
128 assert_eq!(1, counter.wakes.load(atomic::Ordering::SeqCst));
129 assert_eq!(Poll::Ready(9), fut.as_pin_mut().poll(cx));
134 ($($fn_name:ident,)*) => { $(
135 test_future_yields_once_then_returns($fn_name);
144 async_fn_with_internal_borrow,