From 094108026e5e238e136330d0801646db5d049f01 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Fri, 13 Oct 2023 20:06:47 +0200 Subject: [PATCH] perf: generalize specialized full-limb `from_*_bytes` impl --- src/bytes.rs | 50 +++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/src/bytes.rs b/src/bytes.rs index 99ce4ff..cebff39 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -210,19 +210,7 @@ impl Uint { pub const fn from_be_bytes(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. @@ -256,6 +244,18 @@ impl Uint { 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(); @@ -288,18 +288,7 @@ impl Uint { pub const fn from_le_bytes(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. @@ -333,6 +322,17 @@ impl Uint { 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() {