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