rust/tests/ui/async-await/futures-api.rs

62 lines
1.3 KiB
Rust
Raw Normal View History

// run-pass
2019-02-05 22:32:35 -06:00
// aux-build:arc_wake.rs
extern crate arc_wake;
use std::future::Future;
use std::pin::Pin;
use std::sync::{
Arc,
atomic::{self, AtomicUsize},
};
use std::task::{
2019-03-11 18:56:00 -05:00
Context, Poll,
};
2019-02-05 22:32:35 -06:00
use arc_wake::ArcWake;
2019-02-03 14:59:51 -06:00
struct Counter {
wakes: AtomicUsize,
}
2019-02-03 16:59:22 -06:00
impl ArcWake for Counter {
fn wake(self: Arc<Self>) {
Self::wake_by_ref(&self)
}
fn wake_by_ref(arc_self: &Arc<Self>) {
2019-02-03 14:59:51 -06:00
arc_self.wakes.fetch_add(1, atomic::Ordering::SeqCst);
}
}
struct MyFuture;
impl Future for MyFuture {
type Output = ();
2019-03-11 18:56:00 -05:00
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2019-02-03 14:59:51 -06:00
// Wake twice
2019-03-11 18:56:00 -05:00
let waker = cx.waker();
waker.wake_by_ref();
waker.wake_by_ref();
Poll::Ready(())
}
}
2019-02-03 14:59:51 -06:00
fn test_waker() {
let counter = Arc::new(Counter {
2019-02-03 14:59:51 -06:00
wakes: AtomicUsize::new(0),
});
2019-02-03 14:59:51 -06:00
let waker = ArcWake::into_waker(counter.clone());
assert_eq!(2, Arc::strong_count(&counter));
2019-03-11 18:56:00 -05:00
{
let mut context = Context::from_waker(&waker);
assert_eq!(Poll::Ready(()), Pin::new(&mut MyFuture).poll(&mut context));
assert_eq!(2, counter.wakes.load(atomic::Ordering::SeqCst));
}
2019-02-03 14:59:51 -06:00
drop(waker);
assert_eq!(1, Arc::strong_count(&counter));
}
fn main() {
2019-02-03 14:59:51 -06:00
test_waker();
}