joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
Documentation
use std::fmt;
use std::io::{self, Write};

/// The payload of a request or a response.
///
/// This is an opaque type rather than a `Vec<u8>` field because a body that is
/// a vector is a body that is entirely in memory, and a framework whose body
/// type says so can never serve a file or a stream without breaking everyone.
/// Every body this version can build is bytes already in memory. The accessors
/// return `Option` because a streaming body will not be able to answer them,
/// and they are the shape callers have to be writing against before that lands.
///
/// A body is deliberately not `Clone`: a stream cannot be duplicated, so a
/// `Clone` here would freeze the same problem one level down. `Request` and
/// `Response` are therefore not `Clone` either.
#[derive(Default)]
pub struct Body {
    bytes: Vec<u8>,
}

impl Body {
    pub fn empty() -> Body {
        Body { bytes: Vec::new() }
    }

    /// The length, when it is known before a byte is written.
    ///
    /// Always `Some` in this version. A streaming body will answer `None`, and
    /// a response with no known length can only be framed by closing the
    /// connection.
    pub fn len(&self) -> Option<u64> {
        Some(self.bytes.len() as u64)
    }

    /// Whether the body is known to write nothing. `None` when that cannot be
    /// answered without consuming it.
    pub fn is_empty(&self) -> Option<bool> {
        self.len().map(|n| n == 0)
    }

    /// The contents, when the body is already in memory.
    pub fn as_bytes(&self) -> Option<&[u8]> {
        Some(&self.bytes)
    }

    /// Take the contents, when the body is already in memory.
    pub fn into_bytes(self) -> Option<Vec<u8>> {
        Some(self.bytes)
    }

    /// Write the body out. Takes `self` because a stream can only be spent
    /// once, and a signature that allows two writes promises something a
    /// stream cannot keep.
    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 {
        // The contents are request or response data. Printing them turns a
        // debug line, or a `{:?}` in someone's log, into a disclosure.
        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)");
    }
}