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.
13 #![feature(arbitrary_self_types, async_await, await_macro, futures_api, pin)]
17 use std::future::Future;
20 atomic::{self, AtomicUsize},
22 use std::future::FutureObj;
26 local_waker_from_nonlocal,
33 impl Wake for Counter {
34 fn wake(this: &Arc<Self>) {
35 this.wakes.fetch_add(1, atomic::Ordering::SeqCst);
40 impl Spawn for NoopSpawner {
41 fn spawn_obj(&mut self, _: FutureObj<'static, ()>) -> Result<(), SpawnObjError> {
46 struct WakeOnceThenComplete(bool);
48 fn wake_and_yield_once() -> WakeOnceThenComplete { WakeOnceThenComplete(false) }
50 impl Future for WakeOnceThenComplete {
52 fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<()> {
63 fn async_block(x: u8) -> impl Future<Output = u8> {
65 await!(wake_and_yield_once());
70 fn async_nonmove_block(x: u8) -> impl Future<Output = u8> {
73 await!(wake_and_yield_once());
80 fn async_closure(x: u8) -> impl Future<Output = u8> {
81 (async move |x: u8| -> u8 {
82 await!(wake_and_yield_once());
87 async fn async_fn(x: u8) -> u8 {
88 await!(wake_and_yield_once());
92 async fn async_fn_with_borrow(x: &u8) -> u8 {
93 await!(wake_and_yield_once());
97 fn async_fn_with_internal_borrow(y: u8) -> impl Future<Output = u8> {
99 await!(async_fn_with_borrow(&y))
103 unsafe async fn unsafe_async_fn(x: u8) -> u8 {
104 await!(wake_and_yield_once());
115 async fn async_method(x: u8) -> u8 {
117 await!(unsafe_async_fn(x))
122 fn test_future_yields_once_then_returns<F, Fut>(f: F)
124 F: FnOnce(u8) -> Fut,
125 Fut: Future<Output = u8>,
127 let mut fut = PinBox::new(f(9));
128 let counter = Arc::new(Counter { wakes: AtomicUsize::new(0) });
129 let waker = local_waker_from_nonlocal(counter.clone());
130 let spawner = &mut NoopSpawner;
131 let cx = &mut Context::new(&waker, spawner);
133 assert_eq!(0, counter.wakes.load(atomic::Ordering::SeqCst));
134 assert_eq!(Poll::Pending, fut.as_pin_mut().poll(cx));
135 assert_eq!(1, counter.wakes.load(atomic::Ordering::SeqCst));
136 assert_eq!(Poll::Ready(9), fut.as_pin_mut().poll(cx));
141 ($($fn_name:ident,)*) => { $(
142 test_future_yields_once_then_returns($fn_name);
151 async_fn_with_internal_borrow,