MessageBody::boxed

This commit is contained in:
Ali MJ Al-Nasrawy 2021-12-17 01:21:35 +03:00
parent 44b7302845
commit e58dd35701
3 changed files with 34 additions and 2 deletions

View File

@ -14,8 +14,16 @@ use crate::Error;
pub struct BoxBody(Pin<Box<dyn MessageBody<Error = Box<dyn StdError>>>>); pub struct BoxBody(Pin<Box<dyn MessageBody<Error = Box<dyn StdError>>>>);
impl BoxBody { impl BoxBody {
/// Boxes a `MessageBody` and any errors it generates. /// Same as `MessageBody::boxed`.
pub fn new<B>(body: B) -> Self pub fn new<B>(body: B) -> Self
where
B: MessageBody + 'static,
{
body.boxed()
}
/// Boxes a `MessageBody` and any errors it generates.
pub fn new_raw<B>(body: B) -> Self
where where
B: MessageBody + 'static, B: MessageBody + 'static,
{ {
@ -59,6 +67,11 @@ impl MessageBody for BoxBody {
fn take_complete_body(&mut self) -> Bytes { fn take_complete_body(&mut self) -> Bytes {
self.0.take_complete_body() self.0.take_complete_body()
} }
#[inline]
fn boxed(self) -> BoxBody {
self
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -88,6 +88,14 @@ where
EitherBody::Right { body } => body.take_complete_body(), EitherBody::Right { body } => body.take_complete_body(),
} }
} }
#[inline]
fn boxed(self) -> BoxBody {
match self {
EitherBody::Left { body } => body.boxed(),
EitherBody::Right { body } => body.boxed(),
}
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -12,7 +12,7 @@ use bytes::{Bytes, BytesMut};
use futures_core::ready; use futures_core::ready;
use pin_project_lite::pin_project; use pin_project_lite::pin_project;
use super::BodySize; use super::{BodySize, BoxBody};
/// An interface types that can converted to bytes and used as response bodies. /// An interface types that can converted to bytes and used as response bodies.
// TODO: examples // TODO: examples
@ -77,6 +77,17 @@ pub trait MessageBody {
std::any::type_name::<Self>() std::any::type_name::<Self>()
); );
} }
/// Converts this body into `BoxBody`.
///
/// Implementation shouldn't call `BoxBody::new` on `self` as it would cause infinite
/// recursion.
fn boxed(self) -> BoxBody
where
Self: Sized + 'static,
{
BoxBody::new_raw(self)
}
} }
mod foreign_impls { mod foreign_impls {