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 #![feature(arbitrary_self_types, futures_api, pin)]
14 use std::boxed::PinBox;
15 use std::future::Future;
20 atomic::{self, AtomicUsize},
22 use std::future::FutureObj;
25 Wake, Waker, LocalWaker,
26 Executor, SpawnObjError,
27 local_waker, local_waker_from_nonlocal,
31 local_wakes: AtomicUsize,
32 nonlocal_wakes: AtomicUsize,
35 impl Wake for Counter {
36 fn wake(this: &Arc<Self>) {
37 this.nonlocal_wakes.fetch_add(1, atomic::Ordering::SeqCst);
40 unsafe fn wake_local(this: &Arc<Self>) {
41 this.local_wakes.fetch_add(1, atomic::Ordering::SeqCst);
47 impl Executor for NoopExecutor {
48 fn spawn_obj(&mut self, _: FutureObj<'static, ()>) -> Result<(), SpawnObjError> {
55 impl Future for MyFuture {
57 fn poll(self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
58 // Ensure all the methods work appropriately
61 cx.local_waker().wake();
62 cx.executor().spawn_obj(PinBox::new(MyFuture).into()).unwrap();
67 fn test_local_waker() {
68 let counter = Arc::new(Counter {
69 local_wakes: AtomicUsize::new(0),
70 nonlocal_wakes: AtomicUsize::new(0),
72 let waker = unsafe { local_waker(counter.clone()) };
73 let executor = &mut NoopExecutor;
74 let cx = &mut Context::new(&waker, executor);
75 assert_eq!(Poll::Ready(()), PinMut::new(&mut MyFuture).poll(cx));
76 assert_eq!(1, counter.local_wakes.load(atomic::Ordering::SeqCst));
77 assert_eq!(2, counter.nonlocal_wakes.load(atomic::Ordering::SeqCst));
80 fn test_local_as_nonlocal_waker() {
81 let counter = Arc::new(Counter {
82 local_wakes: AtomicUsize::new(0),
83 nonlocal_wakes: AtomicUsize::new(0),
85 let waker: LocalWaker = local_waker_from_nonlocal(counter.clone());
86 let executor = &mut NoopExecutor;
87 let cx = &mut Context::new(&waker, executor);
88 assert_eq!(Poll::Ready(()), PinMut::new(&mut MyFuture).poll(cx));
89 assert_eq!(0, counter.local_wakes.load(atomic::Ordering::SeqCst));
90 assert_eq!(3, counter.nonlocal_wakes.load(atomic::Ordering::SeqCst));
95 test_local_as_nonlocal_waker();