Skip to content

Commit

Permalink
Avoid eagerly allocating too much memory
Browse files Browse the repository at this point in the history
  • Loading branch information
5225225 authored and josecelano committed Sep 25, 2023
1 parent a0947d7 commit decdff6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use serde::{
de::{self, Error as _, Unexpected},
forward_to_deserialize_any,
};
use std::convert::TryFrom;
use std::io::Read;
use std::str;

Expand Down Expand Up @@ -210,11 +211,18 @@ impl<'de, R: Read> Deserializer<R> {

fn parse_bytes(&mut self, len_char: u8) -> Result<Vec<u8>> {
let len = self.parse_bytes_len(len_char)?;
let mut buf = vec![0u8; len];
let mut buf = Vec::new();

let len_usize = u64::try_from(len)
.map_err(|_| Error::InvalidLength(String::from("byte string length too large")))?;

let actual_len = self
.reader
.read(buf.as_mut_slice())
.by_ref()
.take(len_usize)
.read_to_end(&mut buf)
.map_err(Error::IoError)?;

if len != actual_len {
return Err(Error::EndOfStream);
}
Expand Down
5 changes: 5 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,3 +476,8 @@ fn ser_de_flattened_enum() {
},
});
}

#[test]
fn deserialize_too_long_byte_string() {
let _: Result<Value> = from_str("123456789123:1");
}

0 comments on commit decdff6

Please sign in to comment.