1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use super::body::create_error_response;
use super::ResponseBody;
use futures_core::ready;
use http::Response;
use http_body::Body;
use pin_project_lite::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

pin_project! {
    /// Response future for [`RequestBodyLimit`].
    ///
    /// [`RequestBodyLimit`]: super::RequestBodyLimit
    pub struct ResponseFuture<F> {
        #[pin]
        inner: ResponseFutureInner<F>,
    }
}

impl<F> ResponseFuture<F> {
    pub(crate) fn payload_too_large() -> Self {
        Self {
            inner: ResponseFutureInner::PayloadTooLarge,
        }
    }

    pub(crate) fn new(future: F) -> Self {
        Self {
            inner: ResponseFutureInner::Future { future },
        }
    }
}

pin_project! {
    #[project = ResFutProj]
    enum ResponseFutureInner<F> {
        PayloadTooLarge,
        Future {
            #[pin]
            future: F,
        }
    }
}

impl<ResBody, F, E> Future for ResponseFuture<F>
where
    ResBody: Body,
    F: Future<Output = Result<Response<ResBody>, E>>,
{
    type Output = Result<Response<ResponseBody<ResBody>>, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let res = match self.project().inner.project() {
            ResFutProj::PayloadTooLarge => create_error_response(),
            ResFutProj::Future { future } => ready!(future.poll(cx))?.map(ResponseBody::new),
        };

        Poll::Ready(Ok(res))
    }
}