@@ -165,30 +165,45 @@ impl Read for Encoder {
165
165
}
166
166
167
167
// 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 ) {
169
171
// figure out how many bytes we can read. If a len was set, we need
170
172
// to make sure we don't read more than that.
171
173
let upper_bound = match self . res . len ( ) {
172
174
Some ( len) => ( head_bytes_read + len - self . body_bytes_read ) . min ( buf. len ( ) ) ,
173
- None => buf. len ( ) ,
175
+ None => buf. len ( ) - 2 ,
174
176
} ;
175
177
176
178
// Read bytes, and update internal tracking stuff.
177
179
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" ) ;
180
197
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' ;
185
200
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
+ }
190
206
}
191
- debug_assert ! ( self . body_bytes_read <= len, "Too many bytes read. Expected: {}, read: {}" , len, self . body_bytes_read) ;
192
207
}
193
208
}
194
209
0 commit comments