futures_util/future/
lazy.rs
1use super::assert_future;
2use core::pin::Pin;
3use futures_core::future::{FusedFuture, Future};
4use futures_core::task::{Context, Poll};
5
6#[derive(Debug)]
8#[must_use = "futures do nothing unless you `.await` or poll them"]
9pub struct Lazy<F> {
10 f: Option<F>,
11}
12
13impl<F> Unpin for Lazy<F> {}
15
16pub fn lazy<F, R>(f: F) -> Lazy<F>
36where
37 F: FnOnce(&mut Context<'_>) -> R,
38{
39 assert_future::<R, _>(Lazy { f: Some(f) })
40}
41
42impl<F, R> FusedFuture for Lazy<F>
43where
44 F: FnOnce(&mut Context<'_>) -> R,
45{
46 fn is_terminated(&self) -> bool {
47 self.f.is_none()
48 }
49}
50
51impl<F, R> Future for Lazy<F>
52where
53 F: FnOnce(&mut Context<'_>) -> R,
54{
55 type Output = R;
56
57 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
58 Poll::Ready((self.f.take().expect("Lazy polled after completion"))(cx))
59 }
60}