even more byte utils optimizations

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-07-03 20:04:15 +00:00
parent db46d6dd6b
commit 1e8b8cce0f

View file

@ -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<u64> {
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<u64> { 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()?) }