| 1 | use std::pin::Pin; |
| 2 | use std::future::Future; |
| 3 | |
| 4 | use crate::task::{Context, Poll}; |
| 5 | |
| 6 | /// Creates a new future wrapping around a function returning [`Poll`]. |
| 7 | /// |
| 8 | /// Polling the returned future delegates to the wrapped function. |
| 9 | /// |
| 10 | /// # Examples |
| 11 | /// |
| 12 | /// ``` |
| 13 | /// # async_std::task::block_on(async { |
| 14 | /// # |
| 15 | /// use async_std::future; |
| 16 | /// use async_std::task::{Context, Poll}; |
| 17 | /// |
| 18 | /// fn poll_greeting(_: &mut Context<'_>) -> Poll<String> { |
| 19 | /// Poll::Ready("hello world" .to_string()) |
| 20 | /// } |
| 21 | /// |
| 22 | /// assert_eq!(future::poll_fn(poll_greeting).await, "hello world" ); |
| 23 | /// # |
| 24 | /// # }) |
| 25 | /// ``` |
| 26 | pub async fn poll_fn<F, T>(f: F) -> T |
| 27 | where |
| 28 | F: FnMut(&mut Context<'_>) -> Poll<T>, |
| 29 | { |
| 30 | let fut: PollFn = PollFn { f }; |
| 31 | fut.await |
| 32 | } |
| 33 | |
| 34 | struct PollFn<F> { |
| 35 | f: F, |
| 36 | } |
| 37 | |
| 38 | impl<F> Unpin for PollFn<F> {} |
| 39 | |
| 40 | impl<T, F> Future for PollFn<F> |
| 41 | where |
| 42 | F: FnMut(&mut Context<'_>) -> Poll<T>, |
| 43 | { |
| 44 | type Output = T; |
| 45 | |
| 46 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> { |
| 47 | (&mut self.f)(cx) |
| 48 | } |
| 49 | } |
| 50 | |