Skip to content

Commit 0441f20

Browse files
committed
perf: improve pack/unpack endian conversions
1 parent ff87f1c commit 0441f20

1 file changed

Lines changed: 5 additions & 42 deletions

File tree

src/nibbles.rs

Lines changed: 5 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -425,34 +425,9 @@ impl Nibbles {
425425
let len = data.len() * 2;
426426
debug_assert!(len <= NIBBLES);
427427

428-
cfg_if! {
429-
if #[cfg(target_endian = "little")] {
430-
let mut nibbles = U256::ZERO;
431-
let nibbles_slice = unsafe { nibbles.as_le_slice_mut() };
432-
} else {
433-
let mut nibbles_slice = [0u8; 32];
434-
}
435-
}
436-
437-
// Source pointer is at the beginning
438-
let mut src = data.as_ptr().cast::<u8>();
439-
// Move destination pointer to the end of the little endian slice
440-
let mut dst = unsafe { nibbles_slice.as_mut_ptr().add(U256::BYTES) };
441-
// On each iteration, decrement the destination pointer by one, set the destination
442-
// byte, and increment the source pointer by one
443-
for _ in 0..data.len() {
444-
unsafe {
445-
dst = dst.sub(1);
446-
*dst = *src;
447-
src = src.add(1);
448-
}
449-
}
450-
451-
cfg_if! {
452-
if #[cfg(target_endian = "big")] {
453-
let nibbles = U256::from_le_bytes(nibbles_slice);
454-
}
455-
}
428+
let mut be = [0u8; U256::BYTES];
429+
unsafe { be.as_mut_ptr().copy_from_nonoverlapping(data.as_ptr(), data.len()) };
430+
let nibbles = U256::from_be_bytes(be);
456431

457432
Self { len, nibbles }
458433
}
@@ -1135,20 +1110,8 @@ impl<'a> ExactSizeIterator for NibblesIter<'a> {
11351110
unsafe fn pack_to_unchecked(nibbles: &Nibbles, out: &mut [MaybeUninit<u8>]) {
11361111
let byte_len = nibbles.byte_len();
11371112
debug_assert!(out.len() >= byte_len);
1138-
// Move source pointer to the end of the little endian slice
1139-
let sl = as_le_slice(&nibbles.nibbles);
1140-
let mut src = unsafe { sl.as_ptr().add(U256::BYTES) };
1141-
// Destination pointer is at the beginning of the output slice
1142-
let mut dst = out.as_mut_ptr().cast::<u8>();
1143-
// On each iteration, decrement the source pointer by one, set the destination byte, and
1144-
// increment the destination pointer by one
1145-
for _ in 0..byte_len {
1146-
unsafe {
1147-
src = src.sub(1);
1148-
*dst = *src;
1149-
dst = dst.add(1);
1150-
}
1151-
}
1113+
let be = nibbles.nibbles.to_be_bytes::<{ U256::BYTES }>();
1114+
unsafe { out.as_mut_ptr().cast::<u8>().copy_from_nonoverlapping(be.as_ptr(), byte_len) };
11521115
}
11531116

11541117
/// Initializes a smallvec with the given length and a closure that initializes the buffer.

0 commit comments

Comments
 (0)