1 use core::pin::Pin;
2 use futures_core::future::{FusedFuture, Future};
3 use futures_core::task::{Context, Poll};
4 
5 /// Future for the [`lazy`] function.
6 #[derive(Debug)]
7 #[must_use = "futures do nothing unless you `.await` or poll them"]
8 pub struct Lazy<F> {
9     f: Option<F>
10 }
11 
12 // safe because we never generate `Pin<&mut F>`
13 impl<F> Unpin for Lazy<F> {}
14 
15 /// Creates a new future that allows delayed execution of a closure.
16 ///
17 /// The provided closure is only run once the future is polled.
18 ///
19 /// # Examples
20 ///
21 /// ```
22 /// # futures::executor::block_on(async {
23 /// use futures::future;
24 ///
25 /// let a = future::lazy(|_| 1);
26 /// assert_eq!(a.await, 1);
27 ///
28 /// let b = future::lazy(|_| -> i32 {
29 ///     panic!("oh no!")
30 /// });
31 /// drop(b); // closure is never run
32 /// # });
33 /// ```
lazy<F, R>(f: F) -> Lazy<F> where F: FnOnce(&mut Context<'_>) -> R,34 pub fn lazy<F, R>(f: F) -> Lazy<F>
35     where F: FnOnce(&mut Context<'_>) -> R,
36 {
37     Lazy { f: Some(f) }
38 }
39 
40 impl<F, R> FusedFuture for Lazy<F>
41     where F: FnOnce(&mut Context<'_>) -> R,
42 {
is_terminated(&self) -> bool43     fn is_terminated(&self) -> bool { self.f.is_none() }
44 }
45 
46 impl<F, R> Future for Lazy<F>
47     where F: FnOnce(&mut Context<'_>) -> R,
48 {
49     type Output = R;
50 
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R>51     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
52         Poll::Ready((self.f.take().unwrap())(cx))
53     }
54 }
55