Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make count_with more consistent for builtin types. #318

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion binrw/src/binread/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ where
endian: Endian,
args: Self::Args<'_>,
) -> BinResult<Self> {
crate::helpers::count_with(args.count, B::read_options)(reader, endian, args.inner)
crate::helpers::count(args.count)(reader, endian, args.inner)
}
}

Expand Down
60 changes: 32 additions & 28 deletions binrw/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -445,14 +445,40 @@ where
/// # let x: CountBytes = x.read_be().unwrap();
/// # assert_eq!(x.data, &[1, 2, 3]);
/// ```
pub fn count<R, T, Arg, Ret>(n: usize) -> impl Fn(&mut R, Endian, Arg) -> BinResult<Ret>
pub fn count<'a, R, T, Arg, Ret>(n: usize) -> impl Fn(&mut R, Endian, Arg) -> BinResult<Ret>
where
T: for<'a> BinRead<Args<'a> = Arg>,
T: BinRead<Args<'a> = Arg>,
R: Read + Seek,
Arg: Clone,
Ret: FromIterator<T> + 'static,
{
count_with(n, T::read_options)
move |reader, endian, args| {
let mut container = core::iter::empty::<T>().collect::<Ret>();

vec_fast_int!(try (i8 i16 u16 i32 u32 i64 u64 i128 u128) using (container, reader, endian, n) else {
// This extra branch for `Vec<u8>` makes it faster than
// `vec_fast_int`, but *only* because `vec_fast_int` is not allowed
// to use unsafe code to eliminate the unnecessary zero-fill.
// Otherwise, performance would be identical and it could be
// deleted.
if let Some(bytes) = <dyn core::any::Any>::downcast_mut::<Vec<u8>>(&mut container) {
bytes.reserve_exact(n);
let byte_count = reader
.take(n.try_into().map_err(not_enough_bytes)?)
.read_to_end(bytes)?;

if byte_count == n {
Ok(container)
} else {
Err(not_enough_bytes(()))
}
} else {
core::iter::repeat_with(|| T::read_options(reader, endian, args.clone()))
.take(n)
.collect()
}
})
}
}

/// Creates a parser that uses a given function to read N items into a
Expand Down Expand Up @@ -495,31 +521,9 @@ where
Ret: FromIterator<T> + 'static,
{
move |reader, endian, args| {
let mut container = core::iter::empty::<T>().collect::<Ret>();

vec_fast_int!(try (i8 i16 u16 i32 u32 i64 u64 i128 u128) using (container, reader, endian, n) else {
// This extra branch for `Vec<u8>` makes it faster than
// `vec_fast_int`, but *only* because `vec_fast_int` is not allowed
// to use unsafe code to eliminate the unnecessary zero-fill.
// Otherwise, performance would be identical and it could be
// deleted.
if let Some(bytes) = <dyn core::any::Any>::downcast_mut::<Vec<u8>>(&mut container) {
bytes.reserve_exact(n);
let byte_count = reader
.take(n.try_into().map_err(not_enough_bytes)?)
.read_to_end(bytes)?;

if byte_count == n {
Ok(container)
} else {
Err(not_enough_bytes(()))
}
} else {
core::iter::repeat_with(|| read(reader, endian, args.clone()))
.take(n)
.collect()
}
})
core::iter::repeat_with(|| read(reader, endian, args.clone()))
.take(n)
.collect()
}
}

Expand Down
11 changes: 11 additions & 0 deletions binrw/tests/binread_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,14 @@ fn vec_u8() {
binrw::Error::Io(..)
));
}

#[test]
fn count_with_correctness() {
let read = binrw::helpers::count_with(2, binrw::helpers::read_u24);
let _: Vec<u32> = read(
&mut Cursor::new(&[0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF]),
binrw::Endian::Little,
(),
)
.expect("more than 3 bytes per u24 should not be required");
}