1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use rpc::protocol;
use serde_json;
use std::borrow::Cow;
#[derive(Debug)]
pub enum Body<'a> {
Empty,
String(Cow<'a, str>),
Json(Cow<'a, str>),
Bytes(Cow<'a, [u8]>),
}
impl<'a> Body<'a> {
pub fn default_content_type(&self) -> &str {
match self {
Body::Json(_) => "application/json",
Body::Bytes(_) => "application/octet-stream",
_ => "text/plain",
}
}
}
#[doc(hidden)]
impl<'a> From<&'a protocol::TypedData> for Body<'a> {
fn from(data: &'a protocol::TypedData) -> Self {
if data.has_string() {
return Body::String(Cow::Borrowed(data.get_string()));
}
if data.has_json() {
return Body::Json(Cow::Borrowed(data.get_json()));
}
if data.has_bytes() {
return Body::Bytes(Cow::Borrowed(data.get_bytes()));
}
Body::Empty
}
}
impl<'a> From<&'a str> for Body<'a> {
fn from(data: &'a str) -> Self {
Body::String(Cow::Borrowed(data))
}
}
impl<'a> From<String> for Body<'a> {
fn from(data: String) -> Self {
Body::String(Cow::Owned(data))
}
}
impl<'a> From<serde_json::Value> for Body<'a> {
fn from(data: serde_json::Value) -> Self {
Body::Json(Cow::Owned(data.to_string()))
}
}
impl<'a> From<&'a [u8]> for Body<'a> {
fn from(data: &'a [u8]) -> Self {
Body::Bytes(Cow::Borrowed(data))
}
}
impl<'a> From<Vec<u8>> for Body<'a> {
fn from(data: Vec<u8>) -> Self {
Body::Bytes(Cow::Owned(data))
}
}
impl<'a> Into<protocol::TypedData> for Body<'a> {
fn into(self) -> protocol::TypedData {
let mut data = protocol::TypedData::new();
match self {
Body::Empty => {}
Body::String(s) => data.set_string(s.into_owned()),
Body::Json(s) => data.set_json(s.into_owned()),
Body::Bytes(b) => data.set_bytes(b.into_owned()),
};
data
}
}