Skip to main content

g_server/http/
body.rs

1/// The body of an HTTP message.
2#[derive(Debug, Default)]
3pub struct Body {
4    bytes: Vec<u8>,
5}
6
7impl Body {
8    /// Creates an empty body.
9    pub fn empty() -> Self {
10        Self::default()
11    }
12
13    /// Creates a body from bytes.
14    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
15        Self {
16            bytes: bytes.into(),
17        }
18    }
19
20    /// Returns the body as bytes.
21    pub fn as_bytes(&self) -> &[u8] {
22        &self.bytes
23    }
24
25    /// Returns the body length in bytes.
26    pub fn len(&self) -> usize {
27        self.bytes.len()
28    }
29
30    /// Returns whether the body is empty.
31    pub fn is_empty(&self) -> bool {
32        self.bytes.is_empty()
33    }
34
35    /// Consumes the body and returns its bytes.
36    pub fn into_bytes(self) -> Vec<u8> {
37        self.bytes
38    }
39}
40
41impl From<Vec<u8>> for Body {
42    fn from(bytes: Vec<u8>) -> Self {
43        Self::from_bytes(bytes)
44    }
45}
46
47impl From<&[u8]> for Body {
48    fn from(bytes: &[u8]) -> Self {
49        Self::from_bytes(bytes)
50    }
51}
52
53impl From<String> for Body {
54    fn from(value: String) -> Self {
55        Self::from_bytes(value.into_bytes())
56    }
57}
58
59impl From<&str> for Body {
60    fn from(value: &str) -> Self {
61        Self::from_bytes(value.as_bytes())
62    }
63}