Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 5 additions & 13 deletions zerompk/src/bufread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ impl<'a, R: std::io::BufRead> BufReadReader<'a, R> {

#[inline(always)]
fn take_vec(&mut self, len: usize) -> Result<Vec<u8>> {
let mut out = Vec::with_capacity(len);
const CHUNK_SIZE: usize = 8192;
let mut out = Vec::with_capacity(len.min(CHUNK_SIZE));
while out.len() < len {
let buffer = self.window()?;
let count = core::cmp::min(len - out.len(), buffer.len());
Expand Down Expand Up @@ -593,19 +594,10 @@ impl<'de, R: std::io::BufRead> Read<'de> for BufReadReader<'_, R> {
{
out.clear();
let len = self.read_array_len()?;
if out.capacity() < len {
out.reserve(len);
}
let ptr = out.as_mut_ptr();
for initialized in 0..len {
out.reserve(len.min(32));
for _ in 0..len {
match T::read(self) {
Ok(value) => unsafe {
// SAFETY: capacity is at least `len`; every slot is
// initialized once and exposed to Vec immediately so
// unwinding drops all initialized elements.
ptr.add(initialized).write(value);
out.set_len(initialized + 1);
},
Ok(value) => out.push(value),
Err(error) => {
out.clear();
return Err(error);
Expand Down
28 changes: 28 additions & 0 deletions zerompk/tests/deserialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,34 @@ fn test_read_msgpack_bufread_skips_unknown_nested_value() {
assert_eq!(decoded, BufReadKnownField { value: 42 });
}

#[test]
fn test_read_msgpack_bufread_rejects_truncated_huge_payloads_without_preallocating() {
let cases: &[&[u8]] = &[
&[0xdb, 0xff, 0xff, 0xff, 0xff],
&[0xc6, 0xff, 0xff, 0xff, 0xff],
&[0xc9, 0xff, 0xff, 0xff, 0xff, 0x01],
];

for data in cases {
let mut reader = BufReader::with_capacity(1, Cursor::new(*data));
assert!(matches!(
zerompk::read_msgpack_bufread::<_, zerompk::Value<'_>>(&mut reader),
Err(zerompk::Error::BufferTooSmall)
));
}
}

#[test]
fn test_read_msgpack_bufread_rejects_truncated_huge_array_without_preallocating() {
let data = [0xdd, 0xff, 0xff, 0xff, 0xff];
let mut reader = BufReader::with_capacity(1, Cursor::new(data.as_slice()));

assert!(matches!(
zerompk::read_msgpack_bufread::<_, Vec<u64>>(&mut reader),
Err(zerompk::Error::BufferTooSmall)
));
}

#[test]
fn test_read_array_reuses_capacity() {
let mut output = Vec::with_capacity(8);
Expand Down