Remove boxing from StreamBody (#241)

I just had a thought: Why should `response::Headers` be generic, but
`body::StreamBody` should not? `StreamBody` previously boxed the stream
to erase the generics. So we had `response::Headers<T>` but
`body::StreamBody`, without generics.

After thinking about it I think it actually makes sense for responses to
remain generic because you're able to use `impl IntoResponse` so you
don't have to name the generics.

Whereas in the case of `BodyStream` (an extractor) you cannot use `impl Trait`
so it makes sense to box the inner body to make the type easier to name. Besides,
`BodyStream` is mostly useful when the request body isn't `hyper::Body`, as
that already implements `Stream`.
This commit is contained in:
David Pedersen
2021-08-22 22:03:56 +02:00
committed by GitHub
parent b75c34b821
commit a753eac23f
4 changed files with 113 additions and 58 deletions
+22 -2
View File
@@ -1,5 +1,5 @@
use super::{rejection::*, take_body, Extension, FromRequest, RequestParts};
use crate::{BoxError, Error};
use crate::{body::Body, BoxError, Error};
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::stream::Stream;
@@ -171,6 +171,11 @@ where
/// Extractor that extracts the request body as a [`Stream`].
///
/// Note if your request body is [`body::Body`] you can extract that directly
/// and since it already implements [`Stream`] you don't need this type. The
/// purpose of this type is to extract other types of request bodies as a
/// [`Stream`].
///
/// # Example
///
/// ```rust,no_run
@@ -194,6 +199,7 @@ where
/// ```
///
/// [`Stream`]: https://docs.rs/futures/latest/futures/stream/trait.Stream.html
/// [`body::Body`]: crate::body::Body
pub struct BodyStream(
SyncWrapper<Pin<Box<dyn http_body::Body<Data = Bytes, Error = Error> + Send + 'static>>>,
);
@@ -238,6 +244,9 @@ fn body_stream_traits() {
/// Extractor that extracts the raw request body.
///
/// Note that [`body::Body`] can be extracted directly. This purpose of this
/// type is to extract other types of request bodies.
///
/// # Example
///
/// ```rust,no_run
@@ -257,8 +266,10 @@ fn body_stream_traits() {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
///
/// [`body::Body`]: crate::body::Body
#[derive(Debug, Default, Clone)]
pub struct RawBody<B = crate::body::Body>(pub B);
pub struct RawBody<B = Body>(pub B);
#[async_trait]
impl<B> FromRequest<B> for Bytes
@@ -280,6 +291,15 @@ where
}
}
#[async_trait]
impl FromRequest<Body> for Body {
type Rejection = BodyAlreadyExtracted;
async fn from_request(req: &mut RequestParts<Body>) -> Result<Self, Self::Rejection> {
req.take_body().ok_or(BodyAlreadyExtracted)
}
}
#[async_trait]
impl<B> FromRequest<B> for String
where