From 75f0297b507e78f47181d07560e9e0c39aa2bd9f Mon Sep 17 00:00:00 2001 From: Anish Kanthamneni <109305222+akneni@users.noreply.github.com> Date: Fri, 6 Sep 2024 15:29:08 -0400 Subject: [PATCH] feat(http): implement http_body::Body trait for Vec Implement the http_body::Body trait for the Vec type to improve ergonomics when working with byte vectors as HTTP bodies. This change allows Vec to be used directly as a body type in hyper, reducing the need for additional wrappers. --- http-body/src/lib.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/http-body/src/lib.rs b/http-body/src/lib.rs index 70e7f36..614e99d 100644 --- a/http-body/src/lib.rs +++ b/http-body/src/lib.rs @@ -207,6 +207,31 @@ impl Body for String { } } +impl Body for Vec { + type Data = Bytes; + type Error = Infallible; + + fn poll_frame( + mut self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll, Self::Error>>> { + if !self.is_empty() { + let s = std::mem::take(&mut *self); + Poll::Ready(Some(Ok(Frame::data(Bytes::from(s))))) + } else { + Poll::Ready(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>) {}