2 use crate::future::Future;
4 use crate::task::{Context, Poll};
6 /// Creates a future that wraps a function returning [`Poll`].
8 /// Polling the future delegates to the wrapped function. If the returned future is pinned, then the
9 /// captured environment of the wrapped function is also pinned in-place, so as long as the closure
10 /// does not move out of its captures it can soundly create pinned references to them.
15 /// # async fn run() {
16 /// use core::future::poll_fn;
17 /// use std::task::{Context, Poll};
19 /// fn read_line(_cx: &mut Context<'_>) -> Poll<String> {
20 /// Poll::Ready("Hello, World!".into())
23 /// let read_future = poll_fn(read_line);
24 /// assert_eq!(read_future.await, "Hello, World!".to_owned());
27 #[stable(feature = "future_poll_fn", since = "1.64.0")]
28 pub fn poll_fn<T, F>(f: F) -> PollFn<F>
30 F: FnMut(&mut Context<'_>) -> Poll<T>,
35 /// A Future that wraps a function returning [`Poll`].
37 /// This `struct` is created by [`poll_fn()`]. See its
38 /// documentation for more.
39 #[must_use = "futures do nothing unless you `.await` or poll them"]
40 #[stable(feature = "future_poll_fn", since = "1.64.0")]
41 pub struct PollFn<F> {
45 #[stable(feature = "future_poll_fn", since = "1.64.0")]
46 impl<F: Unpin> Unpin for PollFn<F> {}
48 #[stable(feature = "future_poll_fn", since = "1.64.0")]
49 impl<F> fmt::Debug for PollFn<F> {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.debug_struct("PollFn").finish()
55 #[stable(feature = "future_poll_fn", since = "1.64.0")]
56 impl<T, F> Future for PollFn<F>
58 F: FnMut(&mut Context<'_>) -> Poll<T>,
62 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
63 // SAFETY: We are not moving out of the pinned field.
64 (unsafe { &mut self.get_unchecked_mut().f })(cx)