1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#![allow(missing_docs)]
use core::mem::{self, MaybeUninit};
use core::ptr::{self, NonNull};
use core::slice;
#[repr(C)]
pub struct RustSlice {
repr: [MaybeUninit<usize>; mem::size_of::<NonNull<[()]>>() / mem::size_of::<usize>()],
}
impl RustSlice {
pub fn from_ref<T>(slice: &[T]) -> Self {
let ptr = NonNull::from(slice).cast::<T>();
let len = slice.len();
Self::from_raw_parts(ptr, len)
}
pub fn from_mut<T>(slice: &mut [T]) -> Self {
let ptr = NonNull::from(&mut *slice).cast::<T>();
let len = slice.len();
Self::from_raw_parts(ptr, len)
}
pub unsafe fn as_slice<'a, T>(self) -> &'a [T] {
let ptr = self.as_ptr();
let len = self.len();
slice::from_raw_parts(ptr.as_ptr(), len)
}
pub unsafe fn as_mut_slice<'a, T>(self) -> &'a mut [T] {
let ptr = self.as_ptr();
let len = self.len();
slice::from_raw_parts_mut(ptr.as_ptr(), len)
}
pub(crate) fn from_raw_parts<T>(ptr: NonNull<T>, len: usize) -> Self {
let ptr = ptr::slice_from_raw_parts_mut(ptr.as_ptr().cast(), len);
unsafe { mem::transmute::<NonNull<[()]>, RustSlice>(NonNull::new_unchecked(ptr)) }
}
pub(crate) fn as_ptr<T>(&self) -> NonNull<T> {
let rust_slice = RustSlice { repr: self.repr };
let repr = unsafe { mem::transmute::<RustSlice, NonNull<[()]>>(rust_slice) };
repr.cast()
}
pub(crate) fn len(&self) -> usize {
let rust_slice = RustSlice { repr: self.repr };
let repr = unsafe { mem::transmute::<RustSlice, NonNull<[()]>>(rust_slice) };
unsafe { repr.as_ref() }.len()
}
}
const_assert_eq!(mem::size_of::<NonNull<[()]>>(), mem::size_of::<RustSlice>());
const_assert_eq!(
mem::align_of::<NonNull<[()]>>(),
mem::align_of::<RustSlice>(),
);