Skip to main content

ringline_http/
body.rs

1use bytes::Bytes;
2
3/// Request body.
4#[derive(Debug, Clone, Default)]
5pub enum Body {
6    /// No body.
7    #[default]
8    Empty,
9    /// Body from bytes.
10    Bytes(Bytes),
11}
12
13impl Body {
14    /// Returns true if the body is empty.
15    pub fn is_empty(&self) -> bool {
16        match self {
17            Body::Empty => true,
18            Body::Bytes(b) => b.is_empty(),
19        }
20    }
21
22    /// Returns the body as a byte slice, or empty slice if no body.
23    pub fn as_bytes(&self) -> &[u8] {
24        match self {
25            Body::Empty => &[],
26            Body::Bytes(b) => b,
27        }
28    }
29}
30
31impl From<Vec<u8>> for Body {
32    fn from(v: Vec<u8>) -> Self {
33        if v.is_empty() {
34            Body::Empty
35        } else {
36            Body::Bytes(Bytes::from(v))
37        }
38    }
39}
40
41impl From<&[u8]> for Body {
42    fn from(s: &[u8]) -> Self {
43        if s.is_empty() {
44            Body::Empty
45        } else {
46            Body::Bytes(Bytes::copy_from_slice(s))
47        }
48    }
49}
50
51impl From<Bytes> for Body {
52    fn from(b: Bytes) -> Self {
53        if b.is_empty() {
54            Body::Empty
55        } else {
56            Body::Bytes(b)
57        }
58    }
59}
60
61impl From<&str> for Body {
62    fn from(s: &str) -> Self {
63        Body::from(s.as_bytes())
64    }
65}