ntex_util/future/
lazy.rs

1use std::{future::Future, pin::Pin, task::Context, task::Poll};
2
3/// Future for the [`lazy`] function.
4#[derive(Debug)]
5#[must_use = "futures do nothing unless you `.await` or poll them"]
6pub struct Lazy<F> {
7    f: Option<F>,
8}
9
10// safe because we never generate `Pin<&mut F>`
11impl<F> Unpin for Lazy<F> {}
12
13/// Creates a new future that allows delayed execution of a closure.
14///
15/// The provided closure is only run once the future is polled.
16pub fn lazy<F, R>(f: F) -> Lazy<F>
17where
18    F: FnOnce(&mut Context<'_>) -> R,
19{
20    Lazy { f: Some(f) }
21}
22
23impl<F, R> Future for Lazy<F>
24where
25    F: FnOnce(&mut Context<'_>) -> R,
26{
27    type Output = R;
28
29    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<R> {
30        Poll::Ready((self.f.take().expect("Lazy polled after completion"))(cx))
31    }
32}