From 34fdc808e22e73ab9bbf122418a7ba1e1ae32c14 Mon Sep 17 00:00:00 2001 From: Rob Ede Date: Sun, 9 Mar 2025 16:21:24 +0000 Subject: [PATCH] implement from for payload --- actix-http/CHANGES.md | 3 ++- actix-http/src/payload.rs | 38 ++++++++++++++++++++++---------------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/actix-http/CHANGES.md b/actix-http/CHANGES.md index e0698a4ad..703a4cad1 100644 --- a/actix-http/CHANGES.md +++ b/actix-http/CHANGES.md @@ -6,7 +6,8 @@ - Add `header::CLEAR_SITE_DATA` constant. - Add `Extensions::get_or_insert[_with]()` methods. -- Add `dev::Payload::from_[bytes/u8_bytes]()` methods. +- Implement `From` for `Payload`. +- Implement `From>` for `Payload`. ### Changed diff --git a/actix-http/src/payload.rs b/actix-http/src/payload.rs index 11bb78824..d7a52417e 100644 --- a/actix-http/src/payload.rs +++ b/actix-http/src/payload.rs @@ -41,13 +41,31 @@ pin_project! { } impl From for Payload { + #[inline] fn from(payload: crate::h1::Payload) -> Self { Payload::H1 { payload } } } +impl From for Payload { + #[inline] + fn from(bytes: Bytes) -> Self { + let (_, mut pl) = crate::h1::Payload::create(true); + pl.unread_data(bytes); + self::Payload::from(pl) + } +} + +impl From> for Payload { + #[inline] + fn from(vec: Vec) -> Self { + Payload::from(Bytes::from(vec)) + } +} + #[cfg(feature = "http2")] impl From for Payload { + #[inline] fn from(payload: crate::h2::Payload) -> Self { Payload::H2 { payload } } @@ -55,6 +73,7 @@ impl From for Payload { #[cfg(feature = "http2")] impl From<::h2::RecvStream> for Payload { + #[inline] fn from(stream: ::h2::RecvStream) -> Self { Payload::H2 { payload: crate::h2::Payload::new(stream), @@ -63,28 +82,15 @@ impl From<::h2::RecvStream> for Payload { } impl From for Payload { + #[inline] fn from(payload: BoxedPayloadStream) -> Self { Payload::Stream { payload } } } impl Payload { - /// Create Payload from bytes::Bytes - pub fn from_bytes(bytes: bytes::Bytes) -> Payload { - let (_, mut pl) = crate::h1::Payload::create(true); - pl.unread_data(bytes); - self::Payload::from(pl) - } - - /// Create Payload from `Vec` bytes - pub fn from_u8_bytes(u8_bytes: Vec) -> Payload { - let (_, mut pl) = crate::h1::Payload::create(true); - let bytes = bytes::Bytes::from(u8_bytes); - pl.unread_data(bytes); - self::Payload::from(pl) - } - - /// Takes current payload and replaces it with `None` value + /// Takes current payload and replaces it with `None` value. + #[must_use] pub fn take(&mut self) -> Payload { mem::replace(self, Payload::None) }