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
use self::sealed::Sealed;
use crate::error::Error;
use crate::Status;
use bytes::{Buf, Bytes, IntoBuf};
use futures::{try_ready, Poll};
pub use http_body::Body as HttpBody;
use std::fmt;
type BytesBuf = <Bytes as IntoBuf>::Buf;
pub trait Body: Sealed {
type Data: Buf;
type Error: Into<Error>;
fn is_end_stream(&self) -> bool;
fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error>;
fn poll_trailers(&mut self) -> Poll<Option<http::HeaderMap>, Self::Error>;
}
impl<T> Body for T
where
T: HttpBody,
T::Error: Into<Error>,
{
type Data = T::Data;
type Error = T::Error;
fn is_end_stream(&self) -> bool {
HttpBody::is_end_stream(self)
}
fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> {
HttpBody::poll_data(self)
}
fn poll_trailers(&mut self) -> Poll<Option<http::HeaderMap>, Self::Error> {
HttpBody::poll_trailers(self)
}
}
impl<T> Sealed for T
where
T: HttpBody,
T::Error: Into<Error>,
{
}
pub struct BoxBody {
inner: Box<dyn Body<Data = BytesBuf, Error = Status> + Send>,
}
struct MapBody<B>(B);
impl BoxBody {
pub fn new(inner: Box<dyn Body<Data = BytesBuf, Error = Status> + Send>) -> Self {
BoxBody { inner }
}
pub fn map_from<B>(inner: B) -> Self
where
B: Body + Send + 'static,
B::Data: Into<Bytes>,
{
BoxBody::new(Box::new(MapBody(inner)))
}
}
impl HttpBody for BoxBody {
type Data = BytesBuf;
type Error = Status;
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> {
self.inner.poll_data()
}
fn poll_trailers(&mut self) -> Poll<Option<http::HeaderMap>, Self::Error> {
self.inner.poll_trailers()
}
}
impl fmt::Debug for BoxBody {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BoxBody").finish()
}
}
impl<B> HttpBody for MapBody<B>
where
B: Body,
B::Data: Into<Bytes>,
{
type Data = BytesBuf;
type Error = Status;
fn is_end_stream(&self) -> bool {
self.0.is_end_stream()
}
fn poll_data(&mut self) -> Poll<Option<Self::Data>, Self::Error> {
let item = try_ready!(self.0.poll_data().map_err(Status::map_error));
Ok(item.map(|buf| buf.into().into_buf()).into())
}
fn poll_trailers(&mut self) -> Poll<Option<http::HeaderMap>, Self::Error> {
self.0.poll_trailers().map_err(Status::map_error)
}
}
mod sealed {
pub trait Sealed {}
}