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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use std::io::Read;
use std::fs::File;
use std::fmt;
#[derive(Debug)]
pub struct Body {
reader: Kind,
}
impl Body {
pub fn new<R: Read + Send + 'static>(reader: R) -> Body {
Body {
reader: Kind::Reader(Box::new(reader), None),
}
}
pub fn sized<R: Read + Send + 'static>(reader: R, len: u64) -> Body {
Body {
reader: Kind::Reader(Box::new(reader), Some(len)),
}
}
}
#[cfg(test)]
pub fn read_to_string(mut body: Body) -> ::std::io::Result<String> {
let mut s = String::new();
match body.reader {
Kind::Reader(ref mut reader, _) => {
reader.read_to_string(&mut s)
}
Kind::Bytes(ref mut bytes) => {
(&**bytes).read_to_string(&mut s)
}
}.map(|_| s)
}
enum Kind {
Reader(Box<Read + Send>, Option<u64>),
Bytes(Vec<u8>),
}
impl From<Vec<u8>> for Body {
#[inline]
fn from(v: Vec<u8>) -> Body {
Body {
reader: Kind::Bytes(v),
}
}
}
impl From<String> for Body {
#[inline]
fn from(s: String) -> Body {
s.into_bytes().into()
}
}
impl<'a> From<&'a [u8]> for Body {
#[inline]
fn from(s: &'a [u8]) -> Body {
s.to_vec().into()
}
}
impl<'a> From<&'a str> for Body {
#[inline]
fn from(s: &'a str) -> Body {
s.as_bytes().into()
}
}
impl From<File> for Body {
#[inline]
fn from(f: File) -> Body {
let len = f.metadata().map(|m| m.len()).ok();
Body {
reader: Kind::Reader(Box::new(f), len),
}
}
}
impl fmt::Debug for Kind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(),
Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(),
}
}
}
pub fn as_hyper_body(body: &mut Body) -> ::hyper::client::Body {
match body.reader {
Kind::Bytes(ref bytes) => {
let len = bytes.len();
::hyper::client::Body::BufBody(bytes, len)
}
Kind::Reader(ref mut reader, len_opt) => {
match len_opt {
Some(len) => ::hyper::client::Body::SizedBody(reader, len),
None => ::hyper::client::Body::ChunkedBody(reader),
}
}
}
}
pub fn can_reset(body: &Body) -> bool {
match body.reader {
Kind::Bytes(_) => true,
Kind::Reader(..) => false,
}
}