1 use core::mem; 2 use core::ptr::{self, NonNull}; 3 use core::slice; 4 5 #[repr(C)] 6 pub struct RustSlice { 7 pub(crate) repr: NonNull<[()]>, 8 } 9 10 impl RustSlice { from_ref<T>(slice: &[T]) -> Self11 pub fn from_ref<T>(slice: &[T]) -> Self { 12 let ptr = ptr::slice_from_raw_parts::<()>(slice.as_ptr().cast(), slice.len()); 13 RustSlice { 14 repr: unsafe { NonNull::new_unchecked(ptr as *mut _) }, 15 } 16 } 17 from_mut<T>(slice: &mut [T]) -> Self18 pub fn from_mut<T>(slice: &mut [T]) -> Self { 19 let ptr = ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().cast(), slice.len()); 20 RustSlice { 21 repr: unsafe { NonNull::new_unchecked(ptr) }, 22 } 23 } 24 as_slice<'a, T>(self) -> &'a [T]25 pub unsafe fn as_slice<'a, T>(self) -> &'a [T] { 26 let ptr = self.repr.as_ptr(); 27 let len = self.repr.as_ref().len(); 28 slice::from_raw_parts(ptr.cast(), len) 29 } 30 as_mut_slice<'a, T>(self) -> &'a mut [T]31 pub unsafe fn as_mut_slice<'a, T>(self) -> &'a mut [T] { 32 let ptr = self.repr.as_ptr(); 33 let len = self.repr.as_ref().len(); 34 slice::from_raw_parts_mut(ptr.cast(), len) 35 } 36 } 37 38 const_assert_eq!( 39 mem::size_of::<Option<RustSlice>>(), 40 mem::size_of::<RustSlice>(), 41 ); 42