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
use crate::BodyWriter;
use async_trait::async_trait;
use bytes::Bytes;
use conjure_error::Error;
use hyper::header::HeaderValue;
use pin_project::pin_project;
use std::pin::Pin;
#[async_trait]
pub trait Body {
fn content_length(&self) -> Option<u64>;
fn content_type(&self) -> HeaderValue;
fn full_body(&self) -> Option<Bytes> {
None
}
async fn write(self: Pin<&mut Self>, w: Pin<&mut BodyWriter>) -> Result<(), Error>;
async fn reset(self: Pin<&mut Self>) -> bool;
}
pub struct BytesBody {
body: Bytes,
content_type: HeaderValue,
}
impl BytesBody {
pub fn new<T>(body: T, content_type: HeaderValue) -> BytesBody
where
T: Into<Bytes>,
{
BytesBody {
body: body.into(),
content_type,
}
}
}
#[async_trait]
impl Body for BytesBody {
fn content_length(&self) -> Option<u64> {
Some(self.body.len() as u64)
}
fn content_type(&self) -> HeaderValue {
self.content_type.clone()
}
fn full_body(&self) -> Option<Bytes> {
Some(self.body.clone())
}
async fn write(self: Pin<&mut Self>, _: Pin<&mut BodyWriter>) -> Result<(), Error> {
unreachable!()
}
async fn reset(self: Pin<&mut Self>) -> bool {
true
}
}
#[pin_project]
pub(crate) struct ResetTrackingBody<T>
where
T: ?Sized,
{
needs_reset: bool,
#[pin]
body: T,
}
impl<T> ResetTrackingBody<T>
where
T: Body + Send,
{
pub fn new(body: T) -> ResetTrackingBody<T> {
ResetTrackingBody {
needs_reset: false,
body,
}
}
}
impl<T> ResetTrackingBody<T>
where
T: ?Sized,
{
pub fn needs_reset(&self) -> bool {
self.needs_reset
}
}
#[async_trait]
impl<T> Body for ResetTrackingBody<T>
where
T: ?Sized + Body + Send,
{
fn content_length(&self) -> Option<u64> {
self.body.content_length()
}
fn content_type(&self) -> HeaderValue {
self.body.content_type()
}
fn full_body(&self) -> Option<Bytes> {
self.body.full_body()
}
async fn write(self: Pin<&mut Self>, w: Pin<&mut BodyWriter>) -> Result<(), Error> {
let this = self.project();
*this.needs_reset = true;
this.body.write(w).await
}
async fn reset(self: Pin<&mut Self>) -> bool {
let this = self.project();
let ok = this.body.reset().await;
if ok {
*this.needs_reset = false;
}
ok
}
}