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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

62 lines
1.3 KiB
Rust
Raw Normal View History

// run-pass
2019-02-06 04:32:35 +00: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 23:56:00 +00:00
Context, Poll,
};
2019-02-06 04:32:35 +00:00
use arc_wake::ArcWake;
2019-02-03 20:59:51 +00:00
struct Counter {
wakes: AtomicUsize,
}
2019-02-03 22:59:22 +00: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 20:59:51 +00:00
arc_self.wakes.fetch_add(1, atomic::Ordering::SeqCst);
}
}
struct MyFuture;
impl Future for MyFuture {
type Output = ();
2019-03-11 23:56:00 +00:00
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2019-02-03 20:59:51 +00:00
// Wake twice
2019-03-11 23:56:00 +00:00
let waker = cx.waker();
waker.wake_by_ref();
waker.wake_by_ref();
Poll::Ready(())
}
}
2019-02-03 20:59:51 +00:00
fn test_waker() {
let counter = Arc::new(Counter {
2019-02-03 20:59:51 +00:00
wakes: AtomicUsize::new(0),
});
2019-02-03 20:59:51 +00:00
let waker = ArcWake::into_waker(counter.clone());
assert_eq!(2, Arc::strong_count(&counter));
2019-03-11 23:56:00 +00: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 20:59:51 +00:00
drop(waker);
assert_eq!(1, Arc::strong_count(&counter));
}
fn main() {
2019-02-03 20:59:51 +00:00
test_waker();
}