From 1e8b8cce0f6ac62f4dc00ed904b55497e99f79a4 Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Wed, 3 Jul 2024 20:04:15 +0000 Subject: [PATCH] even more byte utils optimizations Signed-off-by: Jason Volk --- src/core/utils/bytes.rs | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/core/utils/bytes.rs b/src/core/utils/bytes.rs index 6ebf4c4f..e8975a49 100644 --- a/src/core/utils/bytes.rs +++ b/src/core/utils/bytes.rs @@ -3,27 +3,28 @@ use crate::Result; #[inline] #[must_use] pub fn increment(old: Option<&[u8]>) -> [u8; 8] { - old.map(TryInto::try_into) - .map_or(0_u64, |val| val.map_or(0_u64, u64::from_be_bytes)) + old.map_or(0_u64, u64_from_bytes_or_zero) .wrapping_add(1) .to_be_bytes() } -/// Parses the big-endian bytes into an u64. -#[inline] -pub fn u64_from_bytes(bytes: &[u8]) -> Result { - let array: [u8; 8] = bytes.try_into()?; - Ok(u64_from_u8x8(array)) -} - -/// Parses the 8 big-endian bytes into an u64. +/// Parses 8 big-endian bytes into an u64; panic on invalid argument #[inline] #[must_use] -pub fn u64_from_u8(bytes: &[u8]) -> u64 { - let bytes: &[u8; 8] = bytes.try_into().expect("must slice at least 8 bytes"); - u64_from_u8x8(*bytes) -} +pub fn u64_from_u8(bytes: &[u8]) -> u64 { u64_from_bytes(bytes).expect("must slice at least 8 bytes") } + +/// Parses the big-endian bytes into an u64. +#[inline] +#[must_use] +pub fn u64_from_bytes_or_zero(bytes: &[u8]) -> u64 { u64_from_bytes(bytes).unwrap_or(0) } + +/// Parses the big-endian bytes into an u64. +#[inline] +pub fn u64_from_bytes(bytes: &[u8]) -> Result { Ok(u64_from_u8x8(*u8x8_from_bytes(bytes)?)) } #[inline] #[must_use] pub fn u64_from_u8x8(bytes: [u8; 8]) -> u64 { u64::from_be_bytes(bytes) } + +#[inline] +pub fn u8x8_from_bytes(bytes: &[u8]) -> Result<&[u8; 8]> { Ok(bytes.try_into()?) }