futures_util/future/
poll_fn.rs

1//! Definition of the `PollFn` adapter combinator
2
3use futures_core::{Future, Poll};
4use futures_core::task;
5
6/// A future which adapts a function returning `Poll`.
7///
8/// Created by the `poll_fn` function.
9#[derive(Debug)]
10#[must_use = "futures do nothing unless polled"]
11pub struct PollFn<F> {
12    inner: F,
13}
14
15/// Creates a new future wrapping around a function returning `Poll`.
16///
17/// Polling the returned future delegates to the wrapped function.
18///
19/// # Examples
20///
21/// ```
22/// # extern crate futures;
23/// use futures::prelude::*;
24/// use futures::future::poll_fn;
25/// use futures::never::Never;
26/// use futures::task;
27///
28/// # fn main() {
29/// fn read_line(cx: &mut task::Context) -> Poll<String, Never> {
30///     Ok(Async::Ready("Hello, World!".into()))
31/// }
32///
33/// let read_future = poll_fn(read_line);
34/// # }
35/// ```
36pub fn poll_fn<T, E, F>(f: F) -> PollFn<F>
37    where F: FnMut(&mut task::Context) -> Poll<T, E>
38{
39    PollFn { inner: f }
40}
41
42impl<T, E, F> Future for PollFn<F>
43    where F: FnMut(&mut task::Context) -> Poll<T, E>
44{
45    type Item = T;
46    type Error = E;
47
48    fn poll(&mut self, cx: &mut task::Context) -> Poll<T, E> {
49        (self.inner)(cx)
50    }
51}