|
| 1 | +use std::future::{join, Future}; |
| 2 | +use std::pin::Pin; |
| 3 | +use std::sync::Arc; |
| 4 | +use std::task::{Context, Poll, Wake}; |
| 5 | +use std::thread; |
| 6 | + |
| 7 | +struct PollN { |
| 8 | + val: usize, |
| 9 | + polled: usize, |
| 10 | + num: usize, |
| 11 | +} |
| 12 | + |
| 13 | +impl Future for PollN { |
| 14 | + type Output = usize; |
| 15 | + |
| 16 | + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 17 | + self.polled += 1; |
| 18 | + |
| 19 | + if self.polled == self.num { |
| 20 | + return Poll::Ready(self.val); |
| 21 | + } |
| 22 | + |
| 23 | + cx.waker().wake_by_ref(); |
| 24 | + Poll::Pending |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +fn poll_n(val: usize, num: usize) -> PollN { |
| 29 | + PollN { val, num, polled: 0 } |
| 30 | +} |
| 31 | + |
| 32 | +#[test] |
| 33 | +fn test_join() { |
| 34 | + block_on(async move { |
| 35 | + let x = join!(async { 0 }); |
| 36 | + assert_eq!(x, 0); |
| 37 | + |
| 38 | + let x = join!(async { 0 }, async { 1 }); |
| 39 | + assert_eq!(x, (0, 1)); |
| 40 | + |
| 41 | + let x = join!(async { 0 }, async { 1 }, async { 2 }); |
| 42 | + assert_eq!(x, (0, 1, 2)); |
| 43 | + |
| 44 | + let x = join!( |
| 45 | + poll_n(0, 1), |
| 46 | + poll_n(1, 5), |
| 47 | + poll_n(2, 2), |
| 48 | + poll_n(3, 1), |
| 49 | + poll_n(4, 2), |
| 50 | + poll_n(5, 3), |
| 51 | + poll_n(6, 4), |
| 52 | + poll_n(7, 1) |
| 53 | + ); |
| 54 | + assert_eq!(x, (0, 1, 2, 3, 4, 5, 6, 7)); |
| 55 | + }); |
| 56 | +} |
| 57 | + |
| 58 | +fn block_on(fut: impl Future) { |
| 59 | + struct Waker; |
| 60 | + impl Wake for Waker { |
| 61 | + fn wake(self: Arc<Self>) { |
| 62 | + thread::current().unpark() |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + let waker = Arc::new(Waker).into(); |
| 67 | + let mut cx = Context::from_waker(&waker); |
| 68 | + let mut fut = Box::pin(fut); |
| 69 | + |
| 70 | + loop { |
| 71 | + match fut.as_mut().poll(&mut cx) { |
| 72 | + Poll::Ready(_) => break, |
| 73 | + Poll::Pending => thread::park(), |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments