async_std/future/poll_fn.rs
1use std::pin::Pin;
2use std::future::Future;
3
4use 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/// ```
26pub async fn poll_fn<F, T>(f: F) -> T
27where
28 F: FnMut(&mut Context<'_>) -> Poll<T>,
29{
30 let fut = PollFn { f };
31 fut.await
32}
33
34struct PollFn<F> {
35 f: F,
36}
37
38impl<F> Unpin for PollFn<F> {}
39
40impl<T, F> Future for PollFn<F>
41where
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}