1mod unknown;
4pub(crate) use unknown::Unknown;
5
6use crate::{BoxError, Error};
7use bytes::Bytes;
8use futures_core::{Stream, TryStream};
9use http_body::{Body as _, Frame};
10use http_body_util::BodyExt;
11use pin_project_lite::pin_project;
12use std::pin::Pin;
13use std::task::{ready, Context, Poll};
14use sync_wrapper::SyncWrapper;
15
16type BoxBody = http_body_util::combinators::UnsyncBoxBody<Bytes, Error>;
17
18fn boxed<B>(body: B) -> BoxBody
19where
20 B: http_body::Body<Data = Bytes> + Send + 'static,
21 B::Error: Into<BoxError>,
22{
23 try_downcast(body).unwrap_or_else(|body| body.map_err(Error::new).boxed_unsync())
24}
25
26pub(crate) fn try_downcast<T, K>(k: K) -> Result<T, K>
27where
28 T: 'static,
29 K: Send + 'static,
30{
31 let mut k = Some(k);
32 if let Some(k) = <dyn std::any::Any>::downcast_mut::<Option<T>>(&mut k) {
33 Ok(k.take().unwrap())
34 } else {
35 Err(k.unwrap())
36 }
37}
38
39#[must_use]
41#[derive(Debug)]
42pub struct Body(BoxBody);
43
44impl Body {
45 pub fn new<B>(body: B) -> Self
47 where
48 B: http_body::Body<Data = Bytes> + Send + 'static,
49 B::Error: Into<BoxError>,
50 {
51 try_downcast(body).unwrap_or_else(|body| Self(boxed(body)))
52 }
53
54 pub fn empty() -> Self {
56 Self::new(http_body_util::Empty::new())
57 }
58
59 pub fn unknown() -> Self {
80 Self::new(Unknown::new())
81 }
82
83 pub fn from_stream<S>(stream: S) -> Self
87 where
88 S: TryStream + Send + 'static,
89 S::Ok: Into<Bytes>,
90 S::Error: Into<BoxError>,
91 {
92 Self::new(StreamBody {
93 stream: SyncWrapper::new(stream),
94 })
95 }
96
97 pub fn into_data_stream(self) -> BodyDataStream {
104 BodyDataStream { inner: self }
105 }
106}
107
108impl Default for Body {
109 fn default() -> Self {
110 Self::empty()
111 }
112}
113
114impl From<()> for Body {
115 fn from(_: ()) -> Self {
116 Self::empty()
117 }
118}
119
120macro_rules! body_from_impl {
121 ($ty:ty) => {
122 impl From<$ty> for Body {
123 fn from(buf: $ty) -> Self {
124 Self::new(http_body_util::Full::from(buf))
125 }
126 }
127 };
128}
129
130body_from_impl!(&'static [u8]);
131body_from_impl!(std::borrow::Cow<'static, [u8]>);
132body_from_impl!(Vec<u8>);
133
134body_from_impl!(&'static str);
135body_from_impl!(std::borrow::Cow<'static, str>);
136body_from_impl!(String);
137
138body_from_impl!(Bytes);
139
140impl http_body::Body for Body {
141 type Data = Bytes;
142 type Error = Error;
143
144 #[inline]
145 fn poll_frame(
146 mut self: Pin<&mut Self>,
147 cx: &mut Context<'_>,
148 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
149 Pin::new(&mut self.0).poll_frame(cx)
150 }
151
152 #[inline]
153 fn size_hint(&self) -> http_body::SizeHint {
154 self.0.size_hint()
155 }
156
157 #[inline]
158 fn is_end_stream(&self) -> bool {
159 self.0.is_end_stream()
160 }
161}
162
163#[must_use]
167#[derive(Debug)]
168pub struct BodyDataStream {
169 inner: Body,
170}
171
172impl Stream for BodyDataStream {
173 type Item = Result<Bytes, Error>;
174
175 #[inline]
176 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
177 loop {
178 match ready!(Pin::new(&mut self.inner).poll_frame(cx)?) {
179 Some(frame) => match frame.into_data() {
180 Ok(data) => return Poll::Ready(Some(Ok(data))),
181 Err(_frame) => {}
182 },
183 None => return Poll::Ready(None),
184 }
185 }
186 }
187}
188
189impl http_body::Body for BodyDataStream {
190 type Data = Bytes;
191 type Error = Error;
192
193 #[inline]
194 fn poll_frame(
195 mut self: Pin<&mut Self>,
196 cx: &mut Context<'_>,
197 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
198 Pin::new(&mut self.inner).poll_frame(cx)
199 }
200
201 #[inline]
202 fn is_end_stream(&self) -> bool {
203 self.inner.is_end_stream()
204 }
205
206 #[inline]
207 fn size_hint(&self) -> http_body::SizeHint {
208 self.inner.size_hint()
209 }
210}
211
212pin_project! {
213 struct StreamBody<S> {
214 #[pin]
215 stream: SyncWrapper<S>,
216 }
217}
218
219impl<S> http_body::Body for StreamBody<S>
220where
221 S: TryStream,
222 S::Ok: Into<Bytes>,
223 S::Error: Into<BoxError>,
224{
225 type Data = Bytes;
226 type Error = Error;
227
228 fn poll_frame(
229 self: Pin<&mut Self>,
230 cx: &mut Context<'_>,
231 ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
232 let stream = self.project().stream.get_pin_mut();
233 match ready!(stream.try_poll_next(cx)) {
234 Some(Ok(chunk)) => Poll::Ready(Some(Ok(Frame::data(chunk.into())))),
235 Some(Err(err)) => Poll::Ready(Some(Err(Error::new(err)))),
236 None => Poll::Ready(None),
237 }
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use futures_core::Stream;
244
245 use crate::body::{try_downcast, Body};
246
247 #[test]
248 fn test_try_downcast() {
249 assert_eq!(try_downcast::<i32, _>(5_u32), Err(5_u32));
250 assert_eq!(try_downcast::<i32, _>(5_i32), Ok(5_i32));
251 }
252
253 #[test]
254 fn data_stream_size_hints() {
255 let stream = Body::empty().into_data_stream();
256 assert_eq!(Stream::size_hint(&stream), (0, None));
257 let body_hint = http_body::Body::size_hint(&stream);
258 assert_eq!(body_hint.lower(), 0);
259 assert_eq!(body_hint.upper(), Some(0));
260
261 let stream = Body::from("hello").into_data_stream();
262 assert_eq!(Stream::size_hint(&stream), (0, None));
263 let body_hint = http_body::Body::size_hint(&stream);
264 assert_eq!(body_hint.lower(), 5);
265 assert_eq!(body_hint.upper(), Some(5));
266
267 let stream = Body::from_stream(stream).into_data_stream();
268 assert_eq!(Stream::size_hint(&stream), (0, None));
269 let body_hint = http_body::Body::size_hint(&stream);
270 assert_eq!(body_hint.lower(), 0);
271 assert_eq!(body_hint.upper(), None);
272 }
273}