Skip to main content

reqmd_http/response/
body.rs

1#[derive(Debug, Clone, PartialEq, Eq, Default)]
2#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
3pub enum ResponseBody {
4    /// No body is present in the response.
5    #[default]
6    None,
7
8    /// Body is a UTF-8 encoded text.
9    Text(String),
10
11    /// Body is a binary representation of data.
12    Binary(Vec<u8>),
13}
14
15impl ResponseBody {
16    /// shorthand to reference body text if it is UTF-8 encoded.
17    pub fn text(&self) -> Option<&str> {
18        match self {
19            ResponseBody::Text(text) => Some(text.as_str()),
20            ResponseBody::None => Some(""),
21            ResponseBody::Binary(_) => None,
22        }
23    }
24
25    /// shorthand to reference body data as a byte slice.
26    pub fn data(&self) -> &[u8] {
27        match self {
28            ResponseBody::None => &[],
29            ResponseBody::Binary(data) => data.as_slice(),
30            ResponseBody::Text(text) => text.as_bytes(),
31        }
32    }
33
34    /// byte-size of body data.
35    pub fn len(&self) -> usize {
36        self.data().len()
37    }
38
39    /// a body with no data.
40    pub fn is_empty(&self) -> bool {
41        self.len() == 0
42    }
43}