hyper_util/common/
lazy.rs

1use pin_project_lite::pin_project;
2
3use std::future::Future;
4use std::pin::Pin;
5use std::task::{self, Poll};
6
7pub(crate) trait Started: Future {
8    fn started(&self) -> bool;
9}
10
11pub(crate) fn lazy<F, R>(func: F) -> Lazy<F, R>
12where
13    F: FnOnce() -> R,
14    R: Future + Unpin,
15{
16    Lazy {
17        inner: Inner::Init { func },
18    }
19}
20
21// FIXME: allow() required due to `impl Trait` leaking types to this lint
22pin_project! {
23    #[allow(missing_debug_implementations)]
24    pub(crate) struct Lazy<F, R> {
25        #[pin]
26        inner: Inner<F, R>,
27    }
28}
29
30pin_project! {
31    #[project = InnerProj]
32    #[project_replace = InnerProjReplace]
33    enum Inner<F, R> {
34        Init { func: F },
35        Fut { #[pin] fut: R },
36        Empty,
37    }
38}
39
40impl<F, R> Started for Lazy<F, R>
41where
42    F: FnOnce() -> R,
43    R: Future,
44{
45    fn started(&self) -> bool {
46        match self.inner {
47            Inner::Init { .. } => false,
48            Inner::Fut { .. } | Inner::Empty => true,
49        }
50    }
51}
52
53impl<F, R> Future for Lazy<F, R>
54where
55    F: FnOnce() -> R,
56    R: Future,
57{
58    type Output = R::Output;
59
60    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
61        let mut this = self.project();
62
63        if let InnerProj::Fut { fut } = this.inner.as_mut().project() {
64            return fut.poll(cx);
65        }
66
67        match this.inner.as_mut().project_replace(Inner::Empty) {
68            InnerProjReplace::Init { func } => {
69                this.inner.set(Inner::Fut { fut: func() });
70                if let InnerProj::Fut { fut } = this.inner.project() {
71                    return fut.poll(cx);
72                }
73                unreachable!()
74            }
75            _ => unreachable!("lazy state wrong"),
76        }
77    }
78}