]> git.lizzy.rs Git - rust.git/blob - library/core/src/future/poll_fn.rs
Auto merge of #103295 - ishitatsuyuki:ninja, r=cuviper
[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. 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.
11 ///
12 /// # Examples
13 ///
14 /// ```
15 /// # async fn run() {
16 /// use core::future::poll_fn;
17 /// use std::task::{Context, Poll};
18 ///
19 /// fn read_line(_cx: &mut Context<'_>) -> Poll<String> {
20 ///     Poll::Ready("Hello, World!".into())
21 /// }
22 ///
23 /// let read_future = poll_fn(read_line);
24 /// assert_eq!(read_future.await, "Hello, World!".to_owned());
25 /// # }
26 /// ```
27 #[stable(feature = "future_poll_fn", since = "1.64.0")]
28 pub fn poll_fn<T, F>(f: F) -> PollFn<F>
29 where
30     F: FnMut(&mut Context<'_>) -> Poll<T>,
31 {
32     PollFn { f }
33 }
34
35 /// A Future that wraps a function returning [`Poll`].
36 ///
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> {
42     f: F,
43 }
44
45 #[stable(feature = "future_poll_fn", since = "1.64.0")]
46 impl<F: Unpin> Unpin for PollFn<F> {}
47
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()
52     }
53 }
54
55 #[stable(feature = "future_poll_fn", since = "1.64.0")]
56 impl<T, F> Future for PollFn<F>
57 where
58     F: FnMut(&mut Context<'_>) -> Poll<T>,
59 {
60     type Output = T;
61
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)
65     }
66 }