Files
axum/src/body.rs
T

97 lines
2.3 KiB
Rust
Raw Normal View History

2021-05-30 04:28:24 +02:00
use bytes::Buf;
2021-06-01 00:34:09 +02:00
use futures_util::ready;
2021-05-30 13:24:03 +02:00
use http_body::{Body as _, Empty};
2021-05-30 04:28:24 +02:00
use std::{
fmt,
pin::Pin,
task::{Context, Poll},
};
2021-05-30 13:24:03 +02:00
pub use hyper::body::Body;
2021-06-01 00:34:09 +02:00
use crate::BoxStdError;
2021-05-30 04:28:24 +02:00
/// A boxed [`Body`] trait object.
pub struct BoxBody<D, E> {
2021-05-30 13:24:03 +02:00
inner: Pin<Box<dyn http_body::Body<Data = D, Error = E> + Send + Sync + 'static>>,
2021-05-30 04:28:24 +02:00
}
impl<D, E> BoxBody<D, E> {
/// Create a new `BoxBody`.
pub fn new<B>(body: B) -> Self
where
2021-05-30 13:24:03 +02:00
B: http_body::Body<Data = D, Error = E> + Send + Sync + 'static,
2021-05-30 04:28:24 +02:00
D: Buf,
{
Self {
inner: Box::pin(body),
}
}
}
2021-05-31 16:28:26 +02:00
// TODO: upstream this to http-body?
2021-05-30 04:28:24 +02:00
impl<D, E> Default for BoxBody<D, E>
where
D: bytes::Buf + 'static,
{
fn default() -> Self {
BoxBody::new(Empty::<D>::new().map_err(|err| match err {}))
}
}
impl<D, E> fmt::Debug for BoxBody<D, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BoxBody").finish()
}
}
2021-06-01 00:34:09 +02:00
// when we've gotten rid of `BoxStdError` then we can remove this
2021-05-30 13:24:03 +02:00
impl<D, E> http_body::Body for BoxBody<D, E>
2021-05-30 04:28:24 +02:00
where
D: Buf,
2021-06-01 00:34:09 +02:00
E: Into<tower::BoxError>,
2021-05-30 04:28:24 +02:00
{
type Data = D;
2021-06-01 00:34:09 +02:00
type Error = BoxStdError;
2021-05-30 04:28:24 +02:00
fn poll_data(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
2021-06-01 00:34:09 +02:00
match ready!(self.inner.as_mut().poll_data(cx)) {
Some(Ok(chunk)) => Some(Ok(chunk)).into(),
Some(Err(err)) => Some(Err(BoxStdError(err.into()))).into(),
None => None.into(),
}
2021-05-30 04:28:24 +02:00
}
fn poll_trailers(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> {
2021-06-01 00:34:09 +02:00
match ready!(self.inner.as_mut().poll_trailers(cx)) {
Ok(trailers) => Ok(trailers).into(),
Err(err) => Err(BoxStdError(err.into())).into(),
}
2021-05-30 04:28:24 +02:00
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.size_hint()
}
}
2021-06-01 00:34:09 +02:00
impl From<String> for BoxBody<bytes::Bytes, tower::BoxError> {
fn from(s: String) -> Self {
let body = hyper::Body::from(s);
let body = body.map_err(Into::<tower::BoxError>::into);
BoxBody {
inner: Box::pin(body),
}
}
}