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

reduce copies of generic functions to improve compile times #319

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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 @@ -19,7 +19,7 @@ macro_rules! binread_impl {
let mut val = [0; core::mem::size_of::<$type_name>()];
let pos = reader.stream_position()?;

reader.read_exact(&mut val).or_else(crate::__private::restore_position(reader, pos))?;
reader.read_exact(&mut val).or_else(|e| Err(crate::__private::restore_position(reader, pos)(e)))?;
Ok(match endian {
Endian::Big => {
<$type_name>::from_be_bytes(val)
Expand Down
102 changes: 65 additions & 37 deletions binrw/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,43 +612,7 @@ fn not_enough_bytes<T>(_: T) -> Error {
macro_rules! vec_fast_int {
(try ($($Ty:ty)+) using ($list:expr, $reader:expr, $endian:expr, $count:expr) else { $($else:tt)* }) => {
$(if let Some(list) = <dyn core::any::Any>::downcast_mut::<Vec<$Ty>>(&mut $list) {
let mut start = 0;
let mut remaining = $count;
// Allocating and reading from the source in chunks is done to keep
// a bad `count` from causing huge memory allocations that are
// doomed to fail
while remaining != 0 {
// Using a similar strategy as std `default_read_to_end` to
// leverage the memory growth strategy of the underlying Vec
// implementation (in std this will be exponential) using a
// minimum byte allocation
const GROWTH: usize = 32 / core::mem::size_of::<$Ty>();
list.reserve(remaining.min(GROWTH.max(1)));

let items_to_read = remaining.min(list.capacity() - start);
let end = start + items_to_read;

// In benchmarks, this resize decreases performance by 27–40%
// relative to using `unsafe` to write directly to uninitialised
// memory, but nobody ever got fired for buying IBM
list.resize(end, 0);
$reader.read_exact(&mut bytemuck::cast_slice_mut::<_, u8>(&mut list[start..end]))?;

remaining -= items_to_read;
start += items_to_read;
}

if
core::mem::size_of::<$Ty>() != 1
&& (
(cfg!(target_endian = "big") && $endian == crate::Endian::Little)
|| (cfg!(target_endian = "little") && $endian == crate::Endian::Big)
)
{
for value in list.iter_mut() {
*value = value.swap_bytes();
}
}
read_vec_fast_int($reader, $count, $endian, list)?;
Ok($list)
} else)* {
$($else)*
Expand All @@ -657,3 +621,67 @@ macro_rules! vec_fast_int {
}

use vec_fast_int;

trait SwapBytes {
fn swap_bytes(self) -> Self;
}

macro_rules! swap_bytes_impl {
($($ty:ty),*) => {
$(
impl SwapBytes for $ty {
fn swap_bytes(self) -> Self {
<$ty>::swap_bytes(self)
}
}
)*
};
}
swap_bytes_impl!(i8, i16, u16, i32, u32, i64, u64, i128, u128);

fn read_vec_fast_int<T, R>(
reader: &mut R,
count: usize,
endian: Endian,
list: &mut Vec<T>,
) -> BinResult<()>
where
R: Read,
T: Clone + Default + bytemuck::Pod + SwapBytes,
{
let mut start = 0;
let mut remaining = count;
// Allocating and reading from the source in chunks is done to keep
// a bad `count` from causing huge memory allocations that are
// doomed to fail
while remaining != 0 {
// Using a similar strategy as std `default_read_to_end` to
// leverage the memory growth strategy of the underlying Vec
// implementation (in std this will be exponential) using a
// minimum byte allocation
let growth = 32 / core::mem::size_of::<T>();
list.reserve(remaining.min(growth.max(1)));

let items_to_read = remaining.min(list.capacity() - start);
let end = start + items_to_read;

// In benchmarks, this resize decreases performance by 27–40%
// relative to using `unsafe` to write directly to uninitialised
// memory, but nobody ever got fired for buying IBM
list.resize(end, T::default());
reader.read_exact(bytemuck::cast_slice_mut::<_, u8>(&mut list[start..end]))?;

remaining -= items_to_read;
start += items_to_read;
}

if core::mem::size_of::<T>() != 1
&& ((cfg!(target_endian = "big") && endian == crate::Endian::Little)
|| (cfg!(target_endian = "little") && endian == crate::Endian::Big))
{
for value in list.iter_mut() {
*value = value.swap_bytes();
}
}
Ok(())
}
8 changes: 4 additions & 4 deletions binrw/src/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,13 @@ where
args
}

pub fn restore_position<E: Into<Error>, S: Seek, T>(
pub fn restore_position<E: Into<Error>, S: Seek>(
stream: &mut S,
pos: u64,
) -> impl FnOnce(E) -> BinResult<T> + '_ {
) -> impl FnOnce(E) -> Error + '_ {
move |error| match stream.seek(SeekFrom::Start(pos)) {
Ok(_) => Err(error.into()),
Err(seek_error) => Err(restore_position_err(error.into(), seek_error.into())),
Ok(_) => error.into(),
Err(seek_error) => restore_position_err(error.into(), seek_error.into()),
}
}

Expand Down
2 changes: 1 addition & 1 deletion binrw_derive/src/binrw/codegen/read_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub(crate) fn generate(input: &Input, derive_input: &syn::DeriveInput) -> TokenS

let rewind = (needs_rewind || input.magic().is_some()).then(|| {
quote! {
.or_else(#RESTORE_POSITION::<binrw::Error, _, _>(#reader_var, #POS))
.or_else(|e| Err(#RESTORE_POSITION::<binrw::Error, _>(#reader_var, #POS)(e)))
}
});

Expand Down