use core::{
alloc::Layout,
mem::{align_of, size_of},
ops::{Add, BitOr, Shr, Sub, SubAssign},
};
#[cfg(feature = "stable_alloc")]
use allocator_api2::alloc::Allocator;
#[cfg(not(feature = "stable_alloc"))]
use core::alloc::Allocator;
#[inline(always)]
pub fn load_u64_le(buf: &[u8], len: usize) -> u64 {
debug_assert!(len <= buf.len());
let mut data = 0u64;
let ptr: *mut _ = &mut data;
unsafe {
std::ptr::copy_nonoverlapping(buf.as_ptr(), ptr as *mut u8, len);
}
data.to_le()
}
#[inline]
pub fn round_to_pow2<T>(value: T) -> T
where
T: SubAssign
+ Add<Output = T>
+ Sub<Output = T>
+ Shr<Output = T>
+ BitOr<Output = T>
+ Copy
+ From<usize>,
{
let v = value - T::from(1);
let res = match size_of::<T>() {
1 => {
let v = v | (v >> T::from(1));
let v = v | (v >> T::from(2));
v | (v >> T::from(4))
}
2 => {
let v = v | (v >> T::from(1));
let v = v | (v >> T::from(2));
let v = v | (v >> T::from(4));
v | (v >> T::from(8))
}
4 => {
let v = v | (v >> T::from(1));
let v = v | (v >> T::from(2));
let v = v | (v >> T::from(4));
let v = v | (v >> T::from(8));
v | (v >> T::from(16))
}
8 => {
let v = v | (v >> T::from(1));
let v = v | (v >> T::from(2));
let v = v | (v >> T::from(4));
let v = v | (v >> T::from(8));
let v = v | (v >> T::from(16));
v | (v >> T::from(32))
}
_ => v,
};
res + T::from(1)
}
pub enum AllocationKind {
Zeroed,
Uninitialized,
}
pub(crate) fn allocate<T, A: Allocator>(
allocator: &A,
count: usize,
kind: AllocationKind,
) -> *mut T {
let size = size_of::<T>();
let align = align_of::<T>();
let layout = Layout::from_size_align(size * count, align).unwrap();
match kind {
AllocationKind::Zeroed => allocator.allocate_zeroed(layout).unwrap().as_ptr() as *mut T,
AllocationKind::Uninitialized => allocator.allocate(layout).unwrap().as_ptr() as *mut T,
}
}
pub(crate) fn deallocate<T, A: Allocator>(allocator: &A, ptr: *mut T, count: usize) {
let size = size_of::<T>();
let align = align_of::<T>();
let layout = Layout::from_size_align(size * count, align).unwrap();
let raw_ptr = ptr as *mut u8;
let nonnull_ptr = std::ptr::NonNull::new(raw_ptr).unwrap();
unsafe {
allocator.deallocate(nonnull_ptr, layout);
}
}