Skip to content

Commit

Permalink
Cleanup unsafe code
Browse files Browse the repository at this point in the history
  • Loading branch information
DoumanAsh committed Jul 27, 2024
1 parent cc7076d commit ef8cbde
Show file tree
Hide file tree
Showing 6 changed files with 378 additions and 296 deletions.
1 change: 0 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ jobs:
#- name: Miri Test(No SSE2)
# env:
# RUSTFLAGS: "-Ctarget-feature=-sse2"
# MIRIFLAGS: "-Zmiri-tag-raw-pointers"
# run: |
# cargo +nightly miri test --features xxh32,const_xxh32,xxh64,const_xxh64,xxh3,const_xxh3
# cargo +nightly miri test --release --features xxh32,const_xxh32,xxh64,const_xxh64,xxh3,const_xxh3
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@
#[cfg(feature = "std")]
extern crate std;

#[cfg(any(feature = "xxh32", feature = "xxh3", feature = "xxh64"))]
mod utils;

#[cfg(any(feature = "xxh32", feature = "const_xxh32", feature = "xxh3", feature = "const_xxh3"))]
mod xxh32_common;
#[cfg(feature = "xxh32")]
Expand Down
50 changes: 50 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! Utilities of the crate
use core::{ptr, mem};

#[inline(always)]
pub const fn get_aligned_chunk_ref<T: Copy>(input: &[u8], offset: usize) -> &T {
debug_assert!(mem::size_of::<T>() > 0); //Size MUST be positive
debug_assert!(mem::size_of::<T>() <= input.len().saturating_sub(offset)); //Must fit

unsafe {
&*(input.as_ptr().add(offset) as *const T)
}
}

#[inline(always)]
pub const fn get_aligned_chunk<T: Copy>(input: &[u8], offset: usize) -> T {
*get_aligned_chunk_ref(input, offset)
}

#[inline(always)]
pub fn get_unaligned_chunk<T: Copy>(input: &[u8], offset: usize) -> T {
debug_assert!(mem::size_of::<T>() > 0); //Size MUST be positive
debug_assert!(mem::size_of::<T>() <= input.len().saturating_sub(offset)); //Must fit

unsafe {
ptr::read_unaligned(input.as_ptr().add(offset) as *const T)
}
}

#[derive(Debug)]
pub struct Buffer<T> {
pub ptr: T,
pub len: usize,
pub offset: usize,
}

impl Buffer<*mut u8> {
#[inline(always)]
pub fn copy_from_slice(&self, src: &[u8]) {
self.copy_from_slice_by_size(src, src.len())
}

#[inline(always)]
pub fn copy_from_slice_by_size(&self, src: &[u8], len: usize) {
debug_assert!(self.len.saturating_sub(self.offset) >= len);

unsafe {
ptr::copy_nonoverlapping(src.as_ptr(), self.ptr.add(self.offset), len);
}
}
}
Loading

0 comments on commit ef8cbde

Please sign in to comment.