Skip to content

Commit 0343714

Browse files
committed
chunked?
Signed-off-by: Yoshua Wuyts <[email protected]>
1 parent f96c0ee commit 0343714

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

src/server.rs

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -165,30 +165,45 @@ impl Read for Encoder {
165165
}
166166

167167
// Read from the AsyncRead impl on the inner Response struct.
168-
if !self.body_done {
168+
// We must ensure there's space to write at least 2 bytes into the
169+
// response stream.
170+
if !self.body_done && head_bytes_read < (buf.len() + 1) {
169171
// figure out how many bytes we can read. If a len was set, we need
170172
// to make sure we don't read more than that.
171173
let upper_bound = match self.res.len() {
172174
Some(len) => (head_bytes_read + len - self.body_bytes_read).min(buf.len()),
173-
None => buf.len(),
175+
None => buf.len() - 2,
174176
};
175177

176178
// Read bytes, and update internal tracking stuff.
177179
let n = ready!(Pin::new(&mut self.res).poll_read(cx, &mut buf[head_bytes_read..upper_bound]))?;
178-
body_bytes_read += n;
179-
self.body_bytes_read += n;
180+
body_bytes_read += n; // body bytes read on this poll
181+
self.body_bytes_read += n; // total body bytes read on all polls
182+
183+
match self.res.len() {
184+
Some(len) => {
185+
if len == self.body_bytes_read {
186+
self.body_done = true;
187+
}
188+
debug_assert!(self.body_bytes_read <= len, "Too many bytes read. Expected: {}, read: {}", len, self.body_bytes_read);
189+
190+
// If our stream no longer gives bytes, end.
191+
if body_bytes_read == 0 {
192+
self.body_done = true;
193+
}
194+
}
195+
None => {
196+
debug_assert!(buf.len() >= 4, "Buffers should be at least 4 bytes long when using chunked encoding");
180197

181-
// If our stream no longer gives bytes, end.
182-
if body_bytes_read == 0 {
183-
self.body_done = true;
184-
}
198+
buf[n] = b'\r';
199+
buf[n + 1] = b'\n';
185200

186-
// If we know we've read all bytes, end.
187-
if let Some(len) = self.res.len() {
188-
if len == self.body_bytes_read {
189-
self.body_done = true;
201+
if body_bytes_read == 0 {
202+
self.body_done = true;
203+
buf[2] = b'\r';
204+
buf[3] = b'\n';
205+
}
190206
}
191-
debug_assert!(self.body_bytes_read <= len, "Too many bytes read. Expected: {}, read: {}", len, self.body_bytes_read);
192207
}
193208
}
194209

0 commit comments

Comments
 (0)