servicepoint-binding-c/src/mem.rs
2025-05-07 08:53:49 +02:00

30 lines
783 B
Rust

use std::ptr::NonNull;
pub(crate) fn heap_move<T>(x: T) -> *mut T {
Box::into_raw(Box::new(x))
}
pub(crate) fn heap_move_nonnull<T>(x: T) -> NonNull<T> {
NonNull::from(Box::leak(Box::new(x)))
}
pub(crate) fn heap_move_ok<T, E>(x: Result<T, E>) -> *mut T {
x.map(|x| heap_move(x)).unwrap_or(std::ptr::null_mut())
}
pub(crate) fn heap_move_some<T>(x: Option<T>) -> *mut T {
x.map(|x| heap_move(x)).unwrap_or(std::ptr::null_mut())
}
pub(crate) unsafe fn heap_drop<T>(x: NonNull<T>) {
drop(unsafe { heap_remove(x) });
}
pub(crate) unsafe fn heap_remove<T>(x: NonNull<T>) -> T {
unsafe { *Box::from_raw(x.as_ptr()) }
}
pub(crate) unsafe fn heap_clone<T: Clone>(source: NonNull<T>) -> NonNull<T> {
heap_move_nonnull(unsafe { source.as_ref().clone() })
}