Skip to content

Commit

Permalink
Merge pull request #273 from DaniPopes/opt-byte
Browse files Browse the repository at this point in the history
perf: optimize `byte` method
  • Loading branch information
prestwich authored Jul 29, 2023
2 parents e34200e + 03c1bd5 commit 72e092d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
12 changes: 10 additions & 2 deletions src/bits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,17 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
#[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
Expand Down
11 changes: 3 additions & 8 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
Expand All @@ -27,8 +24,7 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
#[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.
Expand All @@ -44,8 +40,7 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
#[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.
Expand Down

0 comments on commit 72e092d

Please sign in to comment.