servicepoint-binding-c/src/byte_slice.rs
Vinzenz Schroeter 6dcd26d1c1
Some checks failed
Rust / build (pull_request) Failing after 1m23s
use NotNull for parameters
2025-04-12 13:01:27 +02:00

44 lines
1.3 KiB
Rust

//! FFI slice helper
use std::ptr::NonNull;
/// Represents a span of memory (`&mut [u8]` ) as a struct usable by C code.
///
/// You should not create an instance of this type in your C code.
///
/// # Safety
///
/// The caller has to make sure that:
///
/// - accesses to the memory pointed to with `start` is never accessed outside `length`
/// - the lifetime of the `CByteSlice` does not outlive the memory it points to, as described in
/// the function returning this type.
/// - an instance of this created from C is never passed to a consuming function, as the rust code
/// will try to free the memory of a potentially separate allocator.
#[repr(C)]
pub struct SPByteSlice {
/// The start address of the memory
pub start: NonNull<u8>,
/// The amount of memory in bytes
pub length: usize,
}
impl SPByteSlice {
pub(crate) unsafe fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.start.as_ptr(), self.length) }
}
pub(crate) unsafe fn as_slice_mut(&self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.start.as_ptr(), self.length)
}
}
pub(crate) unsafe fn from_slice(slice: &mut [u8]) -> Self {
Self {
start: NonNull::new(slice.as_mut_ptr()).unwrap(),
length: slice.len(),
}
}
}