]> git.lizzy.rs Git - rust.git/blob - src/libcore/future/poll_fn.rs
Rollup merge of #73771 - alexcrichton:ignore-unstable, r=estebank,GuillaumeGomez
[rust.git] / src / libcore / 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 /// #![feature(future_poll_fn)]
14 /// # async fn run() {
15 /// use core::future::poll_fn;
16 /// use core::task::{Context, Poll};
17 ///
18 /// fn read_line(_cx: &mut Context<'_>) -> Poll<String> {
19 ///     Poll::Ready("Hello, World!".into())
20 /// }
21 ///
22 /// let read_future = poll_fn(read_line);
23 /// assert_eq!(read_future.await, "Hello, World!".to_owned());
24 /// # };
25 /// ```
26 #[unstable(feature = "future_poll_fn", issue = "72302")]
27 pub fn poll_fn<T, F>(f: F) -> PollFn<F>
28 where
29     F: FnMut(&mut Context<'_>) -> Poll<T>,
30 {
31     PollFn { f }
32 }
33
34 /// A Future that wraps a function returning `Poll`.
35 ///
36 /// This `struct` is created by the [`poll_fn`] function. See its
37 /// documentation for more.
38 ///
39 /// [`poll_fn`]: fn.poll_fn.html
40 #[must_use = "futures do nothing unless you `.await` or poll them"]
41 #[unstable(feature = "future_poll_fn", issue = "72302")]
42 pub struct PollFn<F> {
43     f: F,
44 }
45
46 #[unstable(feature = "future_poll_fn", issue = "72302")]
47 impl<F> Unpin for PollFn<F> {}
48
49 #[unstable(feature = "future_poll_fn", issue = "72302")]
50 impl<F> fmt::Debug for PollFn<F> {
51     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52         f.debug_struct("PollFn").finish()
53     }
54 }
55
56 #[unstable(feature = "future_poll_fn", issue = "72302")]
57 impl<T, F> Future for PollFn<F>
58 where
59     F: FnMut(&mut Context<'_>) -> Poll<T>,
60 {
61     type Output = T;
62
63     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
64         (&mut self.f)(cx)
65     }
66 }