From e58dd3570105a3c56ed6bf696907118017a79c1d Mon Sep 17 00:00:00 2001 From: Ali MJ Al-Nasrawy Date: Fri, 17 Dec 2021 01:21:35 +0300 Subject: [PATCH] MessageBody::boxed --- actix-http/src/body/boxed.rs | 15 ++++++++++++++- actix-http/src/body/either.rs | 8 ++++++++ actix-http/src/body/message_body.rs | 13 ++++++++++++- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/actix-http/src/body/boxed.rs b/actix-http/src/body/boxed.rs index d4737aab8..734df8404 100644 --- a/actix-http/src/body/boxed.rs +++ b/actix-http/src/body/boxed.rs @@ -14,8 +14,16 @@ use crate::Error; pub struct BoxBody(Pin>>>); impl BoxBody { - /// Boxes a `MessageBody` and any errors it generates. + /// Same as `MessageBody::boxed`. pub fn new(body: B) -> Self + where + B: MessageBody + 'static, + { + body.boxed() + } + + /// Boxes a `MessageBody` and any errors it generates. + pub fn new_raw(body: B) -> Self where B: MessageBody + 'static, { @@ -59,6 +67,11 @@ impl MessageBody for BoxBody { fn take_complete_body(&mut self) -> Bytes { self.0.take_complete_body() } + + #[inline] + fn boxed(self) -> BoxBody { + self + } } #[cfg(test)] diff --git a/actix-http/src/body/either.rs b/actix-http/src/body/either.rs index 103b39c5d..3a4082dc9 100644 --- a/actix-http/src/body/either.rs +++ b/actix-http/src/body/either.rs @@ -88,6 +88,14 @@ where 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)] diff --git a/actix-http/src/body/message_body.rs b/actix-http/src/body/message_body.rs index 10a7260f4..ca8a3b2c3 100644 --- a/actix-http/src/body/message_body.rs +++ b/actix-http/src/body/message_body.rs @@ -12,7 +12,7 @@ use bytes::{Bytes, BytesMut}; use futures_core::ready; 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. // TODO: examples @@ -77,6 +77,17 @@ pub trait MessageBody { std::any::type_name::() ); } + + /// 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 {