From e7d0d152fc3e508d649a31cb04f25a847d4d88fe Mon Sep 17 00:00:00 2001 From: cynecx Date: Sun, 4 Feb 2024 20:16:53 +0100 Subject: [PATCH 1/2] Replace modulo ops with bitwise-and equivalent --- src/lib.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 4ccc6f0..e78b1c9 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -420,6 +420,13 @@ pub(crate) fn round_down_to(n: usize, divisor: usize) -> usize { n & !(divisor - 1) } +#[inline] +pub(crate) fn round_mut_ptr_down_to(ptr: *mut u8, divisor: usize) -> *mut u8 { + debug_assert!(divisor > 0); + debug_assert!(divisor.is_power_of_two()); + ptr.wrapping_sub(ptr as usize & (divisor - 1)) +} + // After this point, we try to hit page boundaries instead of powers of 2 const PAGE_STRATEGY_CUTOFF: usize = 0x1000; @@ -1412,8 +1419,7 @@ impl Bump { } let ptr = ptr.wrapping_sub(layout.size()); - let rem = ptr as usize % layout.align(); - let aligned_ptr = ptr.wrapping_sub(rem); + let aligned_ptr = round_mut_ptr_down_to(ptr, layout.align()); if aligned_ptr >= start { let aligned_ptr = NonNull::new_unchecked(aligned_ptr); @@ -1508,7 +1514,7 @@ impl Bump { // at least the requested size. let mut ptr = new_footer.ptr.get().as_ptr().sub(size); // Round the pointer down to the requested alignment. - ptr = ptr.sub(ptr as usize % layout.align()); + ptr = round_mut_ptr_down_to(ptr, layout.align()); debug_assert!( ptr as *const _ <= new_footer, "{:p} <= {:p}", From 6022968c95d5c84fdbb7ecff7ecbc0346d46e60c Mon Sep 17 00:00:00 2001 From: Nick Fitzgerald Date: Fri, 9 Feb 2024 08:32:34 -0800 Subject: [PATCH 2/2] Add doc comment for helper function --- src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib.rs b/src/lib.rs index e78b1c9..600f6ad 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -420,6 +420,7 @@ pub(crate) fn round_down_to(n: usize, divisor: usize) -> usize { n & !(divisor - 1) } +/// Same as `round_down_to` but preserves pointer provenance. #[inline] pub(crate) fn round_mut_ptr_down_to(ptr: *mut u8, divisor: usize) -> *mut u8 { debug_assert!(divisor > 0);