From 03c1bd52d2eaa4adea5cbfd798f68cc1995b52c2 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Wed, 26 Jul 2023 09:41:38 +0200 Subject: [PATCH] perf: optimize `byte` method --- src/bits.rs | 12 ++++++++++-- src/bytes.rs | 11 +++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/bits.rs b/src/bits.rs index 02e47a5..1ad045c 100644 --- a/src/bits.rs +++ b/src/bits.rs @@ -67,9 +67,17 @@ impl Uint { #[inline] #[must_use] #[track_caller] - #[allow(clippy::cast_possible_truncation)] // intentional pub const fn byte(&self, index: usize) -> u8 { - (self.limbs[index / 8] >> ((index % 8) * 8)) as u8 + #[cfg(target_endian = "little")] + { + self.as_le_slice()[index] + } + + #[cfg(target_endian = "big")] + #[allow(clippy::cast_possible_truncation)] // intentional + { + (self.limbs[index / 8] >> ((index % 8) * 8)) as u8 + } } /// Reverses the order of bits in the integer. The least significant bit diff --git a/src/bytes.rs b/src/bytes.rs index 3d2103e..f68105c 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -6,10 +6,7 @@ use crate::{ Uint, }; use alloc::{borrow::Cow, vec::Vec}; -use core::{ - ptr::{addr_of, addr_of_mut}, - slice, -}; +use core::slice; // OPT: *_to_smallvec to avoid allocation. impl Uint { @@ -27,8 +24,7 @@ impl Uint { #[must_use] #[inline(always)] pub const fn as_le_slice(&self) -> &[u8] { - let data = addr_of!(self.limbs).cast(); - unsafe { slice::from_raw_parts(data, Self::BYTES) } + unsafe { slice::from_raw_parts(self.limbs.as_ptr().cast(), Self::BYTES) } } /// Access the underlying store as a mutable little-endian slice of bytes. @@ -44,8 +40,7 @@ impl Uint { #[must_use] #[inline(always)] pub unsafe fn as_le_slice_mut(&mut self) -> &mut [u8] { - let data = addr_of_mut!(self.limbs).cast(); - slice::from_raw_parts_mut(data, Self::BYTES) + unsafe { slice::from_raw_parts_mut(self.limbs.as_mut_ptr().cast(), Self::BYTES) } } /// Access the underlying store as a little-endian bytes.