From 3b235932623ea99303fbe04718baaf2cbc12d88e Mon Sep 17 00:00:00 2001 From: Lucas <24826124+Luro02@users.noreply.github.com> Date: Mon, 11 Nov 2019 22:12:22 +0100 Subject: [PATCH] Add `as_bytes` method to `Body` (#708) --- src/async_impl/body.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/async_impl/body.rs b/src/async_impl/body.rs index dbe2809..3f26723 100644 --- a/src/async_impl/body.rs +++ b/src/async_impl/body.rs @@ -35,6 +35,16 @@ struct WrapStream(S); struct WrapHyper(hyper::Body); impl Body { + /// Returns a reference to the internal data of the `Body`. + /// + /// `None` is returned, if the underlying data is a stream. + pub fn as_bytes(&self) -> Option<&[u8]> { + match &self.inner { + Inner::Reusable(bytes) => Some(bytes.as_ref()), + Inner::Streaming { .. } => None, + } + } + /// Wrap a futures `Stream` in a box inside `Body`. /// /// # Example @@ -339,3 +349,15 @@ impl HttpBody for WrapHyper { HttpBody::size_hint(&self.0) } } + +#[cfg(test)] +mod tests { + use super::Body; + + #[test] + fn test_as_bytes() { + let test_data = b"Test body"; + let body = Body::from(&test_data[..]); + assert_eq!(body.as_bytes(), Some(&test_data[..])); + } +}