use std::fmt;
use std::io::{self, Write};
#[derive(Default)]
pub struct Body {
bytes: Vec<u8>,
}
impl Body {
pub fn empty() -> Body {
Body { bytes: Vec::new() }
}
pub fn len(&self) -> Option<u64> {
Some(self.bytes.len() as u64)
}
pub fn is_empty(&self) -> Option<bool> {
self.len().map(|n| n == 0)
}
pub fn as_bytes(&self) -> Option<&[u8]> {
Some(&self.bytes)
}
pub fn into_bytes(self) -> Option<Vec<u8>> {
Some(self.bytes)
}
pub fn write_to<W: Write>(self, out: &mut W) -> io::Result<()> {
out.write_all(&self.bytes)
}
}
impl fmt::Debug for Body {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.len() {
Some(n) => write!(f, "Body({n} bytes)"),
None => f.write_str("Body(streaming)"),
}
}
}
impl From<Vec<u8>> for Body {
fn from(bytes: Vec<u8>) -> Body {
Body { bytes }
}
}
impl From<&[u8]> for Body {
fn from(bytes: &[u8]) -> Body {
Body {
bytes: bytes.to_vec(),
}
}
}
impl From<String> for Body {
fn from(text: String) -> Body {
Body {
bytes: text.into_bytes(),
}
}
}
impl From<&str> for Body {
fn from(text: &str) -> Body {
Body {
bytes: text.as_bytes().to_vec(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_body_has_a_known_zero_length() {
let body = Body::empty();
assert_eq!(body.len(), Some(0));
assert_eq!(body.is_empty(), Some(true));
assert_eq!(body.as_bytes(), Some(&[][..]));
}
#[test]
fn bytes_round_trip() {
let body = Body::from("hello");
assert_eq!(body.len(), Some(5));
assert_eq!(body.as_bytes(), Some(&b"hello"[..]));
assert_eq!(body.into_bytes().unwrap(), b"hello");
}
#[test]
fn writing_a_body_emits_exactly_its_bytes() {
let mut out = Vec::new();
Body::from(vec![1u8, 2, 3]).write_to(&mut out).unwrap();
assert_eq!(out, vec![1, 2, 3]);
}
#[test]
fn debug_reports_the_size_rather_than_the_contents() {
let body = Body::from("a password");
assert_eq!(format!("{body:?}"), "Body(10 bytes)");
}
}