Skip to content

Commit

Permalink
Merge pull request #332 from DaniPopes/bytes-perf
Browse files Browse the repository at this point in the history
perf: generalize specialized full-limb `from_*_bytes` impl
  • Loading branch information
prestwich authored Oct 15, 2023
2 parents 23fc40f + 4a6074d commit 666cd31
Showing 1 changed file with 25 additions and 25 deletions.
50 changes: 25 additions & 25 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,19 +210,7 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
pub const fn from_be_bytes<const BYTES: usize>(bytes: [u8; BYTES]) -> Self {
// TODO: Use a `const {}` block for this assertion
assert!(BYTES == Self::BYTES, "BYTES must be equal to Self::BYTES");
if BYTES % 8 == 0 {
// Optimized implementation for full-limb types.
let mut limbs = [0; LIMBS];
let end = bytes.as_ptr_range().end;
let mut i = 0;
while i < LIMBS {
limbs[i] = u64::from_be_bytes(unsafe { *end.sub((i + 1) * 8).cast() });
i += 1;
}
Self::from_limbs(limbs)
} else {
Self::from_be_slice(&bytes)
}
Self::from_be_slice(&bytes)
}

/// Creates a new integer from a big endian slice of bytes.
Expand Down Expand Up @@ -256,6 +244,18 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
return None;
}

if Self::BYTES % 8 == 0 && bytes.len() == Self::BYTES {
// Optimized implementation for full-limb types.
let mut limbs = [0; LIMBS];
let end = bytes.as_ptr_range().end;
let mut i = 0;
while i < LIMBS {
limbs[i] = u64::from_be_bytes(unsafe { *end.sub((i + 1) * 8).cast() });
i += 1;
}
return Some(Self::from_limbs(limbs));
}

let mut limbs = [0; LIMBS];
let mut i = 0;
let mut c = bytes.len();
Expand Down Expand Up @@ -288,18 +288,7 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
pub const fn from_le_bytes<const BYTES: usize>(bytes: [u8; BYTES]) -> Self {
// TODO: Use a `const {}` block for this assertion
assert!(BYTES == Self::BYTES, "BYTES must be equal to Self::BYTES");
if BYTES % 8 == 0 {
// Optimized implementation for full-limb types.
let mut limbs = [0; LIMBS];
let mut i = 0;
while i < LIMBS {
limbs[i] = u64::from_le_bytes(unsafe { *bytes.as_ptr().add(i * 8).cast() });
i += 1;
}
Self::from_limbs(limbs)
} else {
Self::from_le_slice(&bytes)
}
Self::from_le_slice(&bytes)
}

/// Creates a new integer from a little endian slice of bytes.
Expand Down Expand Up @@ -333,6 +322,17 @@ impl<const BITS: usize, const LIMBS: usize> Uint<BITS, LIMBS> {
return None;
}

if Self::BYTES % 8 == 0 && bytes.len() == Self::BYTES {
// Optimized implementation for full-limb types.
let mut limbs = [0; LIMBS];
let mut i = 0;
while i < LIMBS {
limbs[i] = u64::from_le_bytes(unsafe { *bytes.as_ptr().add(i * 8).cast() });
i += 1;
}
return Some(Self::from_limbs(limbs));
}

let mut limbs = [0; LIMBS];
let mut i = 0;
while i < bytes.len() {
Expand Down

0 comments on commit 666cd31

Please sign in to comment.