From 730e9bd64caaa07a0724d4624d55f809c6b71873 Mon Sep 17 00:00:00 2001 From: Lucio Franco Date: Fri, 20 May 2022 14:11:48 -0400 Subject: [PATCH] Add String impl for body (#58) --- src/lib.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index b63924f..afaa1d9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,8 +26,9 @@ pub use self::next::{Data, Trailers}; pub use self::size_hint::SizeHint; use self::combinators::{BoxBody, MapData, MapErr, UnsyncBoxBody}; -use bytes::Buf; +use bytes::{Buf, Bytes}; use http::HeaderMap; +use std::convert::Infallible; use std::ops; use std::pin::Pin; use std::task::{Context, Poll}; @@ -283,6 +284,38 @@ impl Body for http::Response { } } +impl Body for String { + type Data = Bytes; + type Error = Infallible; + + fn poll_data( + mut self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll>> { + if !self.is_empty() { + let s = std::mem::take(&mut *self); + Poll::Ready(Some(Ok(s.into_bytes().into()))) + } else { + Poll::Ready(None) + } + } + + fn poll_trailers( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll, Self::Error>> { + Poll::Ready(Ok(None)) + } + + fn is_end_stream(&self) -> bool { + self.is_empty() + } + + fn size_hint(&self) -> SizeHint { + SizeHint::with_exact(self.len() as u64) + } +} + #[cfg(test)] fn _assert_bounds() { fn can_be_trait_object(_: &dyn Body>, Error = std::io::Error>) {}