Skip to content

Commit 9aa6ab8

Browse files
committed
Speedup future::poll_fn
1 parent 4f0ca7b commit 9aa6ab8

File tree

2 files changed

+17
-14
lines changed

2 files changed

+17
-14
lines changed

src/future.rs

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

4+
use core::pin::Pin;
45
use core::task::{Context, Poll};
56

67
/// Create a future that is immediately ready with a value.
@@ -502,18 +503,21 @@ pub fn poll_fn<F, T>(f: F) -> impl Future<Output = T>
502503
where
503504
F: FnMut(&mut Context) -> Poll<T>,
504505
{
505-
use std::future::from_generator;
506-
use std::future::get_task_context;
507-
508-
from_generator(|| {
509-
let mut f = f;
510-
loop {
511-
match get_task_context(|context: &mut Context| f(context)) {
512-
Poll::Pending => yield,
513-
Poll::Ready(value) => return value,
514-
}
506+
struct PollFn<F> {
507+
f: F,
508+
}
509+
impl<F> Unpin for PollFn<F> {}
510+
impl<T, F> Future for PollFn<F>
511+
where
512+
F: FnMut(&mut Context<'_>) -> Poll<T>,
513+
{
514+
type Output = T;
515+
516+
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
517+
(&mut self.f)(cx)
515518
}
516-
})
519+
}
520+
PollFn { f }
517521
}
518522

519523
#[cfg(test)]

src/stream.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,12 @@ use pin_utils::pin_mut;
3030
/// assert_eq!(next(&mut stream).await, None);
3131
/// # });
3232
/// ```
33-
pub async fn next<St>(stream: &mut St) -> Option<St::Item>
33+
pub fn next<'a, St>(mut stream: &'a mut St) -> impl Future<Output = Option<St::Item>> + 'a
3434
where
3535
St: Stream + Unpin,
3636
{
3737
use crate::future::poll_fn;
38-
let future_next = poll_fn(|context| Pin::new(&mut *stream).poll_next(context));
39-
future_next.await
38+
poll_fn(move |context| Pin::new(&mut stream).poll_next(context))
4039
}
4140

4241
/// Collect all of the values of this stream into a vector, returning a

0 commit comments

Comments
 (0)