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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use std::{
    pin::Pin,
    task::{Context, Poll},
};

use futures_util::{Stream, TryStreamExt};
use http_body_util::{combinators::BoxBody, BodyExt, Full, StreamBody};
use hyper::body::{Body, Frame, Incoming, SizeHint};

use crate::{BoxError, Bytes, Error, Result};

/// The incoming body from HTTP [`Request`].
///
/// [`Request`]: crate::Request
#[derive(Debug)]
pub enum IncomingBody {
    /// An empty body.
    Empty,
    /// An incoming body.
    Incoming(Option<Incoming>),
}

impl IncomingBody {
    /// Creates new incoming body.
    #[must_use]
    pub fn new(inner: Option<Incoming>) -> Self {
        Self::Incoming(inner)
    }

    /// The incoming body has been used.
    #[must_use]
    pub fn used() -> Self {
        Self::Incoming(None)
    }
}

impl Default for IncomingBody {
    fn default() -> Self {
        Self::Empty
    }
}

impl Body for IncomingBody {
    type Data = Bytes;
    type Error = Error;

    #[inline]
    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        match self.get_mut() {
            Self::Empty => Poll::Ready(None),
            Self::Incoming(i) => match i {
                None => Poll::Ready(None),
                Some(inner) => match Pin::new(inner).poll_frame(cx)? {
                    Poll::Ready(Some(frame)) => Poll::Ready(Some(Ok(frame))),
                    Poll::Ready(None) => {
                        // the body has been used.
                        *i = None;
                        Poll::Ready(None)
                    }
                    Poll::Pending => Poll::Pending,
                },
            },
        }
    }

    #[inline]
    fn is_end_stream(&self) -> bool {
        match self {
            Self::Empty | Self::Incoming(None) => true,
            Self::Incoming(Some(inner)) => inner.is_end_stream(),
        }
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        match self {
            Self::Empty | Self::Incoming(None) => SizeHint::with_exact(0),
            Self::Incoming(Some(inner)) => inner.size_hint(),
        }
    }
}

impl Stream for IncomingBody {
    type Item = Result<Bytes, BoxError>;

    #[inline]
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match self.get_mut() {
            Self::Empty | Self::Incoming(None) => Poll::Ready(None),
            Self::Incoming(Some(inner)) => match Pin::new(inner).poll_frame(cx)? {
                Poll::Ready(Some(frame)) => Poll::Ready(frame.into_data().map(Ok).ok()),
                Poll::Ready(None) => Poll::Ready(None),
                Poll::Pending => Poll::Pending,
            },
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            Self::Empty | Self::Incoming(None) => (0, Some(0)),
            Self::Incoming(Some(inner)) => {
                let sh = inner.size_hint();
                (
                    usize::try_from(sh.lower()).unwrap_or(usize::MAX),
                    sh.upper().map(|v| usize::try_from(v).unwrap_or(usize::MAX)),
                )
            }
        }
    }
}

/// The outgoing body to HTTP [`Response`].
///
/// [`Response`]: crate::Response
#[derive(Debug)]
pub enum OutgoingBody<D = Bytes> {
    /// An empty body.
    Empty,
    /// A body that consists of a single chunk.
    Full(Full<D>),
    /// A boxed [`Body`] trait object.
    Boxed(BoxBody<D, Error>),
}

impl OutgoingBody {
    /// A body created from a [`Stream`].
    pub fn streaming<S, D, E>(stream: S) -> Self
    where
        S: Stream<Item = Result<D, E>> + Send + Sync + 'static,
        D: Into<Bytes> + 'static,
        E: Into<Error> + 'static,
    {
        Self::Boxed(
            StreamBody::new(
                stream
                    .map_ok(Into::into)
                    .map_ok(Frame::data)
                    .map_err(Into::into),
            )
            .boxed(),
        )
    }
}

impl Default for OutgoingBody {
    fn default() -> Self {
        Self::Empty
    }
}

impl Body for OutgoingBody {
    type Data = Bytes;
    type Error = Error;

    #[inline]
    fn poll_frame(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        match self.get_mut() {
            Self::Empty => Poll::Ready(None),
            Self::Full(full) => Pin::new(full).poll_frame(cx).map_err(Error::from),
            Self::Boxed(body) => Pin::new(body).poll_frame(cx),
        }
    }

    #[inline]
    fn is_end_stream(&self) -> bool {
        match self {
            Self::Empty => true,
            Self::Full(full) => full.is_end_stream(),
            Self::Boxed(body) => body.is_end_stream(),
        }
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        match self {
            Self::Empty => SizeHint::with_exact(0),
            Self::Full(full) => full.size_hint(),
            Self::Boxed(body) => body.size_hint(),
        }
    }
}

impl Stream for OutgoingBody {
    type Item = Result<Bytes, std::io::Error>;

    #[inline]
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match match self.get_mut() {
            Self::Empty => return Poll::Ready(None),
            Self::Full(full) => Pin::new(full)
                .poll_frame(cx)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
            Self::Boxed(body) => Pin::new(body)
                .poll_frame(cx)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?,
        } {
            Poll::Ready(Some(frame)) => Poll::Ready(frame.into_data().map(Ok).ok()),
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let sh = match self {
            Self::Empty => return (0, Some(0)),
            Self::Full(full) => full.size_hint(),
            Self::Boxed(body) => body.size_hint(),
        };
        (
            usize::try_from(sh.lower()).unwrap_or(usize::MAX),
            sh.upper().map(|v| usize::try_from(v).unwrap_or(usize::MAX)),
        )
    }
}

impl<D> From<()> for OutgoingBody<D> {
    fn from((): ()) -> Self {
        Self::Empty
    }
}

impl<D> From<Full<D>> for OutgoingBody<D> {
    fn from(value: Full<D>) -> Self {
        Self::Full(value)
    }
}

impl<D> From<BoxBody<D, Error>> for OutgoingBody<D> {
    fn from(value: BoxBody<D, Error>) -> Self {
        Self::Boxed(value)
    }
}