Skip to content
This repository was archived by the owner on Sep 4, 2024. It is now read-only.

Commit 72bea34

Browse files
committed
simple_http: deserialize json from the reader, don't use an intermediate buffer
1 parent c20033e commit 72bea34

File tree

1 file changed

+10
-20
lines changed

1 file changed

+10
-20
lines changed

src/simple_http.rs

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,6 @@ pub const DEFAULT_PORT: u16 = 8332;
6464
/// The Default SOCKS5 Port to use for proxy connection.
6565
pub const DEFAULT_PROXY_PORT: u16 = 9050;
6666

67-
/// Maximum size of the allocation we initially make for a response
68-
const INITIAL_RESP_ALLOC: u64 = 1024 * 1024;
6967
/// Absolute maximum content length we will allow before cutting off the response
7068
const FINAL_RESP_ALLOC: u64 = 1024 * 1024 * 1024;
7169

@@ -251,35 +249,27 @@ impl SimpleHttpTransport {
251249
// Read up to `content_length` bytes. Note that if there is no content-length
252250
// header, we will assume an effectively infinite content length, i.e. we will
253251
// just keep reading from the socket until it is closed.
254-
let buffer = match content_length {
255-
None => {
256-
let mut buffer = Vec::with_capacity(INITIAL_RESP_ALLOC as usize);
257-
sock.take(FINAL_RESP_ALLOC).read_to_end(&mut buffer)?;
258-
drop(sock_lock);
259-
buffer
260-
},
252+
let mut reader = match content_length {
253+
None => sock.take(FINAL_RESP_ALLOC),
261254
Some(n) if n > FINAL_RESP_ALLOC => {
262255
return Err(Error::HttpResponseContentLengthTooLarge {
263256
length: n,
264257
max: FINAL_RESP_ALLOC,
265258
});
266259
},
267-
Some(n) => {
268-
let mut buffer = Vec::with_capacity(INITIAL_RESP_ALLOC as usize);
269-
let n_read = sock.take(n).read_to_end(&mut buffer)? as u64;
270-
drop(sock_lock);
271-
if n_read < n {
272-
return Err(Error::IncompleteResponse { content_length: n, n_read });
273-
}
274-
buffer
275-
}
260+
Some(n) => sock.take(n),
276261
};
277262

278263
// Attempt to parse the response. Don't check the HTTP error code until
279264
// after parsing, since Bitcoin Core will often return a descriptive JSON
280265
// error structure which is more useful than the error code.
281-
match serde_json::from_slice(&buffer) {
282-
Ok(s) => Ok(s),
266+
match serde_json::from_reader(&mut reader) {
267+
Ok(s) => {
268+
if content_length.is_some() {
269+
reader.bytes().count(); // consume any trailing bytes
270+
}
271+
Ok(s)
272+
}
283273
Err(e) => {
284274
// If the response was not 200, assume the parse failed because of that
285275
if response_code != 200 {

0 commit comments

Comments
 (0)