Skip to content

Commit 63e6e91

Browse files
authored
http::Body: add bytes_contents, like contents but gives Bytes (#132)
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<Bytes>, this makes a corresponding accessor.
1 parent f93a8cf commit 63e6e91

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

‎src/http/body.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ pub mod util {
4747
/// * `async fn Body::contents(&mut self) -> Result<&[u8], Error>` is ready
4848
/// when all contents of the body have been collected, and gives them as a
4949
/// byte slice.
50+
/// * `async fn Body::bytes_contents(&mut self) -> Result<Bytes, Error>` is
51+
/// the same as `Body::contents`, except returns the `Bytes` type instead of
52+
/// a byte slice.
5053
/// * `async fn Body::str_contents(&mut self) -> Result<&str, Error>` is ready
5154
/// when all contents of the body have been collected, and gives them as a str
5255
/// slice.
@@ -170,6 +173,16 @@ impl Body {
170173
}
171174
}
172175
}
176+
/// Collect the entire contents of this `Body`, and expose it as `Bytes`.
177+
/// This async fn will be pending until the entire `Body` is
178+
/// copied into memory, or an error occurs.
179+
pub async fn bytes_contents(&mut self) -> Result<Bytes, Error> {
180+
let _ = self.contents().await?;
181+
match &self.0 {
182+
BodyInner::Complete { data, .. } => Ok(data.clone()),
183+
_ => unreachable!(),
184+
}
185+
}
173186

174187
/// Get a value for the length of this `Body`'s content, in bytes, if
175188
/// known. This value can come from either the Content-Length header

0 commit comments

Comments
 (0)