Skip to content

Commit ae5685a

Browse files
committed
Implement stream::poll_fn
1 parent be9797e commit ae5685a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/stream/poll_fn.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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<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+
/// ```
32+
pub fn poll_fn<T, E, F>(f: F) -> PollFn<F>
33+
where
34+
F: FnMut() -> Poll<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+
46+
fn poll(&mut self) -> Poll<Option<T>, E> {
47+
(self.inner)()
48+
}
49+
}

0 commit comments

Comments
 (0)