1//! Definition of the `PollFn` adapter combinator
2
3use super::assert_future;
4use core::fmt;
5use core::pin::Pin;
6use futures_core::future::Future;
7use futures_core::task::{Context, Poll};
8
9/// Future for the [`poll_fn`] function.
10#[must_use = "futures do nothing unless you `.await` or poll them"]
11pub struct PollFn<F> {
12 f: F,
13}
14
15impl<F> Unpin for PollFn<F> {}
16
17/// Creates a new future wrapping around a function returning [`Poll`].
18///
19/// Polling the returned future delegates to the wrapped function.
20///
21/// # Examples
22///
23/// ```
24/// # futures::executor::block_on(async {
25/// use futures::future::poll_fn;
26/// use futures::task::{Context, Poll};
27///
28/// fn read_line(_cx: &mut Context<'_>) -> Poll<String> {
29/// Poll::Ready("Hello, World!".into())
30/// }
31///
32/// let read_future = poll_fn(read_line);
33/// assert_eq!(read_future.await, "Hello, World!".to_owned());
34/// # });
35/// ```
36pub fn poll_fn<T, F>(f: F) -> PollFn<F>
37where
38 F: FnMut(&mut Context<'_>) -> Poll<T>,
39{
40 assert_future::<T, _>(PollFn { f })
41}
42
43impl<F> fmt::Debug for PollFn<F> {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.debug_struct(name:"PollFn").finish()
46 }
47}
48
49impl<T, F> Future for PollFn<F>
50where
51 F: FnMut(&mut Context<'_>) -> Poll<T>,
52{
53 type Output = T;
54
55 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
56 (&mut self.f)(cx)
57 }
58}
59