Skip to content

Commit 4d93e62

Browse files
committed
Add future::poll_fn implementation
1 parent 38e8937 commit 4d93e62

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Future
2525
- [x] future::map_err
2626
- [x] future::map_ok
2727
- [x] future::or_else
28-
- [ ] future::poll_fn
28+
- [x] future::poll_fn
2929
- [x] future::ready
3030
- [x] future::then
3131
- [x] future::unwrap_or_else

src/future.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use futures::future::Future;
22
use futures::stream::Stream;
33

4+
use core::task::{Poll, Waker};
5+
46
pub async fn ready<T>(value: T) -> T {
57
value
68
}
@@ -137,6 +139,24 @@ pub fn into_stream<Fut>(future: Fut) -> impl Stream<Item = Fut::Output>
137139
})
138140
}
139141

142+
pub fn poll_fn<F, T>(f: F) -> impl Future<Output = T>
143+
where F: FnMut(&Waker) -> Poll<T>,
144+
{
145+
use std::future::from_generator;
146+
use std::future::get_task_waker;
147+
148+
from_generator(|| {
149+
let mut f = f;
150+
loop {
151+
let poll_result = get_task_waker(|waker: &_| f(waker));
152+
match poll_result {
153+
Poll::Pending => yield,
154+
Poll::Ready(value) => return value,
155+
}
156+
}
157+
})
158+
}
159+
140160
#[cfg(test)]
141161
mod tests {
142162
use futures::executor;
@@ -264,4 +284,17 @@ mod tests {
264284
assert_eq!(collected, vec![17]);
265285
});
266286
}
287+
288+
#[test]
289+
fn test_poll_fn() {
290+
executor::block_on(async {
291+
let read_line = |_waker: &_| -> Poll<String> {
292+
Poll::Ready("Hello, World!".into())
293+
};
294+
295+
let read_future = poll_fn(read_line);
296+
assert_eq!(await!(read_future), "Hello, World!".to_owned());
297+
});
298+
}
299+
267300
}

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#![feature(async_await, await_macro, futures_api)]
1+
#![feature(async_await, await_macro, futures_api, gen_future, generators)]
22

33
pub mod future;
44
pub mod stream;

0 commit comments

Comments
 (0)