safa_api/
raw.rs

1use core::ptr::NonNull;
2
3#[repr(C)]
4#[derive(Debug)]
5pub struct RawSlice<T> {
6    ptr: *const T,
7    len: usize,
8}
9
10impl<T> RawSlice<T> {
11    #[inline(always)]
12    pub unsafe fn from_raw_parts(ptr: *const T, len: usize) -> Self {
13        Self { ptr, len }
14    }
15    #[inline(always)]
16    pub unsafe fn from_slice(slice: &[T]) -> Self {
17        Self {
18            ptr: slice.as_ptr(),
19            len: slice.len(),
20        }
21    }
22
23    #[inline(always)]
24    pub fn len(&self) -> usize {
25        self.len
26    }
27
28    #[inline(always)]
29    pub fn as_ptr(&self) -> *const T {
30        self.ptr
31    }
32}
33
34impl<T> RawSliceMut<T> {
35    #[inline(always)]
36    pub unsafe fn from_raw_parts(ptr: *mut T, len: usize) -> Self {
37        Self { ptr, len }
38    }
39
40    #[inline(always)]
41    pub fn len(&self) -> usize {
42        self.len
43    }
44
45    #[inline(always)]
46    pub fn as_ptr(&self) -> *const T {
47        self.ptr
48    }
49
50    #[inline(always)]
51    pub fn as_mut_ptr(&self) -> *mut T {
52        self.ptr
53    }
54}
55
56impl<T> RawSliceMut<RawSlice<T>> {
57    /// Converts a slice of slices of [`T`] into [`RawSliceMut<RawSlice<T>>`]
58    /// # Safety
59    /// `slices` becomes invaild after use
60    /// as it is going to be reused as a memory location for creating `Self`
61    /// making this unexpensive but dangerous
62    /// O(N) expect if the Layout of RawSlice is equal to the Layout of rust slices, and it has been optimized it is O(1)
63    #[inline(always)]
64    pub unsafe fn from_slices(slices: *mut [&[T]]) -> Self {
65        let old_slices = unsafe { &mut *slices };
66        let raw_slices = unsafe { &mut *(slices as *mut [RawSlice<T>]) };
67
68        for (i, slice) in old_slices.iter().enumerate() {
69            raw_slices[i] = unsafe { RawSlice::from_slice(slice) };
70        }
71        unsafe { RawSliceMut::from_raw_parts(raw_slices.as_mut_ptr(), raw_slices.len()) }
72    }
73}
74
75#[repr(C)]
76#[derive(Debug)]
77pub struct RawSliceMut<T> {
78    ptr: *mut T,
79    len: usize,
80}
81
82#[repr(C)]
83#[derive(Debug)]
84pub struct NonNullSlice<T> {
85    ptr: NonNull<T>,
86    len: usize,
87}
88
89impl<T> NonNullSlice<T> {
90    pub const unsafe fn from_raw_parts(ptr: NonNull<T>, len: usize) -> Self {
91        Self { ptr, len }
92    }
93}
94
95/// A C complitable Option-like type
96#[derive(Debug)]
97#[repr(C)]
98pub enum Optional<T> {
99    None,
100    Some(T),
101}
102
103impl<T> From<Option<T>> for Optional<T> {
104    #[inline(always)]
105    fn from(value: Option<T>) -> Self {
106        match value {
107            None => Self::None,
108            Some(x) => Self::Some(x),
109        }
110    }
111}