1use bytes::Bytes;
2
3#[derive(Debug, Clone, Default)]
5pub enum Body {
6 #[default]
8 Empty,
9 Bytes(Bytes),
11 Text(String),
13 Json(serde_json::Value),
15}
16
17impl Body {
18 pub fn is_empty(&self) -> bool {
20 matches!(self, Body::Empty)
21 }
22
23 pub fn as_text(&self) -> Option<&str> {
25 match self {
26 Body::Text(s) => Some(s.as_str()),
27 _ => None,
28 }
29 }
30}
31
32impl From<String> for Body {
34 fn from(s: String) -> Self {
35 Body::Text(s)
36 }
37}
38
39impl From<&str> for Body {
40 fn from(s: &str) -> Self {
41 Body::Text(s.to_string())
42 }
43}
44
45impl From<Bytes> for Body {
46 fn from(b: Bytes) -> Self {
47 Body::Bytes(b)
48 }
49}
50
51impl From<Vec<u8>> for Body {
52 fn from(v: Vec<u8>) -> Self {
53 Body::Bytes(Bytes::from(v))
54 }
55}
56
57impl From<serde_json::Value> for Body {
58 fn from(v: serde_json::Value) -> Self {
59 Body::Json(v)
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn test_body_default_is_empty() {
69 let body = Body::default();
70 assert!(body.is_empty());
71 }
72
73 #[test]
74 fn test_body_from_string() {
75 let body = Body::from("hello".to_string());
76 assert_eq!(body.as_text(), Some("hello"));
77 }
78
79 #[test]
80 fn test_body_from_str() {
81 let body = Body::from("world");
82 assert_eq!(body.as_text(), Some("world"));
83 }
84
85 #[test]
86 fn test_body_from_bytes() {
87 let body = Body::from(Bytes::from_static(b"data"));
88 assert!(!body.is_empty());
89 assert!(matches!(body, Body::Bytes(_)));
90 }
91
92 #[test]
93 fn test_body_from_json() {
94 let val = serde_json::json!({"key": "value"});
95 let body = Body::from(val.clone());
96 assert!(matches!(body, Body::Json(_)));
97 }
98}