]> git.lizzy.rs Git - rust.git/blob - library/core/src/future/poll_fn.rs
Stabilize `future_poll_fn`
[rust.git] / library / core / src / future / poll_fn.rs
1 use crate::fmt;
2 use crate::future::Future;
3 use crate::pin::Pin;
4 use crate::task::{Context, Poll};
5
6 /// Creates a future that wraps a function returning [`Poll`].
7 ///
8 /// Polling the future delegates to the wrapped function.
9 ///
10 /// # Examples
11 ///
12 /// ```
13 /// # async fn run() {
14 /// use core::future::poll_fn;
15 /// use std::task::{Context, Poll};
16 ///
17 /// fn read_line(_cx: &mut Context<'_>) -> Poll<String> {
18 ///     Poll::Ready("Hello, World!".into())
19 /// }
20 ///
21 /// let read_future = poll_fn(read_line);
22 /// assert_eq!(read_future.await, "Hello, World!".to_owned());
23 /// # }
24 /// ```
25 #[stable(feature = "future_poll_fn", since = "1.64.0")]
26 pub fn poll_fn<T, F>(f: F) -> PollFn<F>
27 where
28     F: FnMut(&mut Context<'_>) -> Poll<T>,
29 {
30     PollFn { f }
31 }
32
33 /// A Future that wraps a function returning [`Poll`].
34 ///
35 /// This `struct` is created by [`poll_fn()`]. See its
36 /// documentation for more.
37 #[must_use = "futures do nothing unless you `.await` or poll them"]
38 #[stable(feature = "future_poll_fn", since = "1.64.0")]
39 pub struct PollFn<F> {
40     f: F,
41 }
42
43 #[stable(feature = "future_poll_fn", since = "1.64.0")]
44 impl<F> Unpin for PollFn<F> {}
45
46 #[stable(feature = "future_poll_fn", since = "1.64.0")]
47 impl<F> fmt::Debug for PollFn<F> {
48     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49         f.debug_struct("PollFn").finish()
50     }
51 }
52
53 #[stable(feature = "future_poll_fn", since = "1.64.0")]
54 impl<T, F> Future for PollFn<F>
55 where
56     F: FnMut(&mut Context<'_>) -> Poll<T>,
57 {
58     type Output = T;
59
60     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
61         (&mut self.f)(cx)
62     }
63 }