From 03c581799c8de9ea6c86ab0e984d2a85b707a693 Mon Sep 17 00:00:00 2001 From: Pat Hickey Date: Mon, 15 Jun 2026 15:18:03 -0700 Subject: [PATCH] http::Body: add bytes_contents, like contents but gives Bytes Its trivial for the library to provide this efficient implementation, but building one out of the `contents` method will be inefficient and cost a copy. Since the Body constructors includes From, this makes a corresponding accessor. --- src/http/body.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/http/body.rs b/src/http/body.rs index c23a3c0..50773d6 100644 --- a/src/http/body.rs +++ b/src/http/body.rs @@ -47,6 +47,9 @@ pub mod util { /// * `async fn Body::contents(&mut self) -> Result<&[u8], Error>` is ready /// when all contents of the body have been collected, and gives them as a /// byte slice. +/// * `async fn Body::bytes_contents(&mut self) -> Result` is +/// the same as `Body::contents`, except returns the `Bytes` type instead of +/// a byte slice. /// * `async fn Body::str_contents(&mut self) -> Result<&str, Error>` is ready /// when all contents of the body have been collected, and gives them as a str /// slice. @@ -170,6 +173,16 @@ impl Body { } } } + /// Collect the entire contents of this `Body`, and expose it as `Bytes`. + /// This async fn will be pending until the entire `Body` is + /// copied into memory, or an error occurs. + pub async fn bytes_contents(&mut self) -> Result { + let _ = self.contents().await?; + match &self.0 { + BodyInner::Complete { data, .. } => Ok(data.clone()), + _ => unreachable!(), + } + } /// Get a value for the length of this `Body`'s content, in bytes, if /// known. This value can come from either the Content-Length header