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