xxhash_rust/
utils.rs

1//! Utilities of the crate
2use core::{ptr, mem};
3
4#[inline(always)]
5pub const fn get_aligned_chunk_ref<T: Copy>(input: &[u8], offset: usize) -> &T {
6    debug_assert!(mem::size_of::<T>() > 0); //Size MUST be positive
7    debug_assert!(mem::size_of::<T>() <= input.len().saturating_sub(offset)); //Must fit
8
9    unsafe {
10        &*(input.as_ptr().add(offset) as *const T)
11    }
12}
13
14#[allow(unused)]
15#[inline(always)]
16pub const fn get_aligned_chunk<T: Copy>(input: &[u8], offset: usize) -> T {
17    *get_aligned_chunk_ref(input, offset)
18}
19
20#[inline(always)]
21pub fn get_unaligned_chunk<T: Copy>(input: &[u8], offset: usize) -> T {
22    debug_assert!(mem::size_of::<T>() > 0); //Size MUST be positive
23    debug_assert!(mem::size_of::<T>() <= input.len().saturating_sub(offset)); //Must fit
24
25    unsafe {
26        ptr::read_unaligned(input.as_ptr().add(offset) as *const T)
27    }
28}
29
30#[derive(Debug)]
31pub struct Buffer<T> {
32    pub ptr: T,
33    pub len: usize,
34    pub offset: usize,
35}
36
37impl Buffer<*mut u8> {
38    #[inline(always)]
39    pub fn copy_from_slice(&self, src: &[u8]) {
40        self.copy_from_slice_by_size(src, src.len())
41    }
42
43    #[inline(always)]
44    pub fn copy_from_slice_by_size(&self, src: &[u8], len: usize) {
45        debug_assert!(self.len.saturating_sub(self.offset) >= len);
46
47        unsafe {
48            ptr::copy_nonoverlapping(src.as_ptr(), self.ptr.add(self.offset), len);
49        }
50    }
51}