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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
mod sync_reader;
pub use sync_reader::BodySyncReader;
use sync_reader::sync_reader_into_bytes;
mod async_reader;
pub use async_reader::BodyAsyncReader;
use async_reader::async_reader_into_bytes;
mod async_bytes_streamer;
pub use async_bytes_streamer::BodyAsyncBytesStreamer;
use async_bytes_streamer::async_bytes_streamer_into_bytes;
mod body_http;
pub use body_http::BodyHttp;
use body_http::IncomingAsAsyncBytesStream;
use std::{io, fmt, mem};
use std::pin::Pin;
use std::io::Read as SyncRead;
use std::time::Duration;
use tokio::task;
use tokio::io::AsyncRead;
use futures_core::Stream as AsyncStream;
use hyper::body::Incoming;
use bytes::Bytes;
type PinnedAsyncRead = Pin<Box<dyn AsyncRead + Send + Sync>>;
type BoxedSyncRead = Box<dyn SyncRead + Send + Sync>;
type PinnedAsyncBytesStream = Pin<Box<
dyn AsyncStream<Item=io::Result<Bytes>> + Send + Sync
>>;
enum Inner {
Empty,
Bytes(Bytes),
Incoming(Incoming),
SyncReader(BoxedSyncRead),
AsyncReader(PinnedAsyncRead),
AsyncBytesStreamer(PinnedAsyncBytesStream)
}
impl fmt::Debug for Inner {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Empty => f.write_str("Empty"),
Self::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
Self::Incoming(_) => f.write_str("Incoming"),
Self::SyncReader(_) => f.write_str("SyncReader"),
Self::AsyncReader(_) => f.write_str("AsyncReader"),
Self::AsyncBytesStreamer(_) => f.write_str("AsyncBytesStreamer")
}
}
}
impl Default for Inner {
fn default() -> Self {
Self::Empty
}
}
#[derive(Debug, Clone, Default)]
struct Constraints {
timeout: Option<Duration>,
size: Option<usize>
}
#[derive(Debug, Default)]
pub struct Body {
inner: Inner,
constraints: Constraints
}
impl Body {
fn new_inner(inner: Inner) -> Self {
Self {
inner,
constraints: Constraints::default()
}
}
pub fn new() -> Self {
Self::new_inner(Inner::Empty)
}
pub fn from_bytes(bytes: impl Into<Bytes>) -> Self {
let bytes = bytes.into();
if !bytes.is_empty() {
Self::new_inner(Inner::Bytes(bytes))
} else {
Self::new()
}
}
pub fn copy_from_slice(slice: impl AsRef<[u8]>) -> Self {
let slice = slice.as_ref();
if !slice.is_empty() {
Self::new_inner(Inner::Bytes(Bytes::copy_from_slice(slice)))
} else {
Self::new()
}
}
pub fn from_incoming(incoming: Incoming) -> Self {
Self::new_inner(Inner::Incoming(incoming))
}
pub fn from_sync_reader<R>(reader: R) -> Self
where R: SyncRead + Send + Sync + 'static {
Self::new_inner(Inner::SyncReader(Box::new(reader)))
}
pub fn from_async_reader<R>(reader: R) -> Self
where R: AsyncRead + Send + Sync + 'static {
Self::new_inner(Inner::AsyncReader(Box::pin(reader)))
}
pub fn from_async_bytes_streamer<S>(streamer: S) -> Self
where S: AsyncStream<Item=io::Result<Bytes>> + Send + Sync + 'static {
Self::new_inner(Inner::AsyncBytesStreamer(Box::pin(streamer)))
}
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub fn serialize<S: ?Sized>(value: &S) -> io::Result<Self>
where S: serde::Serialize {
serde_json::to_vec(value)
.map(|v| v.into())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
pub fn is_empty(&self) -> bool {
matches!(self.inner, Inner::Empty)
}
pub fn len(&self) -> Option<usize> {
match &self.inner {
Inner::Empty => Some(0),
Inner::Bytes(b) => Some(b.len()),
_ => None
}
}
pub fn set_size_limit(&mut self, size: Option<usize>) {
self.constraints.size = size;
}
pub fn set_timeout(&mut self, timeout: Option<Duration>) {
self.constraints.timeout = timeout;
}
pub fn take(&mut self) -> Self {
mem::take(self)
}
pub async fn into_bytes(self) -> io::Result<Bytes> {
match self.inner {
Inner::Empty => Ok(Bytes::new()),
Inner::Bytes(b) => {
if let Some(size_limit) = self.constraints.size {
if b.len() > size_limit {
return Err(size_limit_reached("Bytes to big"))
}
}
Ok(b)
},
Inner::Incoming(i) => {
async_bytes_streamer_into_bytes(
IncomingAsAsyncBytesStream::new(i),
self.constraints
).await
},
Inner::SyncReader(r) => {
task::spawn_blocking(|| {
sync_reader_into_bytes(r, self.constraints)
}).await
.map_err(join_error)?
},
Inner::AsyncReader(r) => {
async_reader_into_bytes(r, self.constraints).await
},
Inner::AsyncBytesStreamer(s) => {
async_bytes_streamer_into_bytes(s, self.constraints).await
}
}
}
pub async fn into_string(self) -> io::Result<String> {
let bytes = self.into_bytes().await?;
String::from_utf8(bytes.into())
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
pub fn into_sync_reader(self) -> BodySyncReader {
BodySyncReader::new(self.inner, self.constraints)
}
pub fn into_async_reader(self) -> BodyAsyncReader {
BodyAsyncReader::new(self.inner, self.constraints)
}
pub fn into_async_bytes_streamer(self) -> BodyAsyncBytesStreamer {
BodyAsyncBytesStreamer::new(self.inner, self.constraints)
}
pub fn into_http_body(self) -> BodyHttp {
BodyHttp::new(self.inner, self.constraints)
}
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub async fn deserialize<D>(self) -> io::Result<D>
where D: serde::de::DeserializeOwned + Send + 'static {
let reader = self.into_sync_reader();
if reader.needs_spawn_blocking() {
task::spawn_blocking(|| serde_json::from_reader(reader)).await
.map_err(join_error)?
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
} else {
serde_json::from_reader(reader)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
}
}
impl From<Bytes> for Body {
fn from(b: Bytes) -> Self {
Self::from_bytes(b)
}
}
impl From<Vec<u8>> for Body {
fn from(b: Vec<u8>) -> Self {
Self::from_bytes(b)
}
}
impl From<String> for Body {
fn from(s: String) -> Self {
Self::from_bytes(s)
}
}
impl From<&'static str> for Body {
fn from(s: &'static str) -> Self {
Self::from_bytes(Bytes::from_static(s.as_bytes()))
}
}
impl From<Incoming> for Body {
fn from(i: Incoming) -> Self {
Self::from_incoming(i)
}
}
fn size_limit_reached(msg: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::UnexpectedEof, msg)
}
fn timed_out(msg: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::TimedOut, msg)
}
fn join_error(error: task::JoinError) -> io::Error {
io::Error::new(io::ErrorKind::Other, error)
}