Add as_bytes method to Body (#708)

This commit is contained in:
Lucas
2019-11-11 22:12:22 +01:00
committed by Sean McArthur
parent 1ce6731f2d
commit 3b23593262

View File

@@ -35,6 +35,16 @@ struct WrapStream<S>(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[..]));
}
}