Skip to content

Commit 90febe2

Browse files
Return empty vec for read_to_end ZST (sharksforarms#566)
* Return an empty vec when instructed to read to end or certain bytes but the struct is a ZST
1 parent b94bc11 commit 90febe2

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

src/impls/vec.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use core::mem;
2+
13
use no_std_io::io::{Read, Seek, Write};
24

35
#[cfg(feature = "alloc")]
@@ -40,6 +42,11 @@ where
4042
Ctx: Copy,
4143
Predicate: FnMut(usize, &T) -> bool,
4244
{
45+
// ZST detected, return empty vec
46+
if mem::size_of::<T>() == 0 {
47+
return Ok(Vec::new());
48+
}
49+
4350
let mut res = capacity.map_or_else(Vec::new, Vec::with_capacity);
4451

4552
let start_read = reader.bits_read;
@@ -67,6 +74,11 @@ where
6774
T: DekuReader<'a, Ctx>,
6875
Ctx: Copy,
6976
{
77+
// ZST detected, return empty vec
78+
if mem::size_of::<T>() == 0 {
79+
return Ok(Vec::new());
80+
}
81+
7082
let mut res = capacity.map_or_else(Vec::new, Vec::with_capacity);
7183
loop {
7284
if reader.end() {

tests/test_struct.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,3 +230,36 @@ fn test_units() {
230230
let new_bytes = a.to_bytes().unwrap();
231231
assert_eq!(bytes, &*new_bytes);
232232
}
233+
234+
/// Issue 513
235+
#[test]
236+
fn test_zst_vec_1() {
237+
#[derive(Debug, PartialEq, DekuRead)]
238+
struct EmptyThing {}
239+
240+
#[derive(Debug, PartialEq, DekuRead)]
241+
struct ListOfThings {
242+
#[deku(read_all)]
243+
things: Vec<EmptyThing>,
244+
}
245+
246+
let bytes = vec![];
247+
let (y, x) = ListOfThings::from_bytes((&bytes, 0)).unwrap();
248+
assert_eq!(x.things.len(), 0);
249+
}
250+
/// Issue 513
251+
#[test]
252+
fn test_zst_vec_2() {
253+
#[derive(Debug, PartialEq, DekuRead)]
254+
struct EmptyThing {}
255+
256+
#[derive(Debug, PartialEq, DekuRead)]
257+
struct ListOfThings {
258+
#[deku(bytes_read = "1")]
259+
things: Vec<EmptyThing>,
260+
}
261+
262+
let bytes = vec![];
263+
let (y, x) = ListOfThings::from_bytes((&bytes, 0)).unwrap();
264+
assert_eq!(x.things.len(), 0);
265+
}

0 commit comments

Comments
 (0)