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
use std::io::Read;
use std::fs::File;
pub struct Body {
reader: Kind,
}
impl Body {
pub fn new<R: Read + 'static>(reader: R) -> Body {
Body {
reader: Kind::Reader(Box::new(reader), None),
}
}
}
enum Kind {
Reader(Box<Read>, 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),
}
}
}
pub fn as_hyper_body<'a>(body: &'a mut Body) -> ::hyper::client::Body<'a> {
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),
}
}
}
}