unify heap allocation handling

This commit is contained in:
Vinzenz Schroeter 2025-04-12 18:05:01 +02:00
commit fd6f9198f3
10 changed files with 101 additions and 110 deletions

View file

@ -1,4 +1,4 @@
use crate::ByteSlice;
use crate::{heap_drop, heap_move, heap_move_nonnull, ByteSlice};
use servicepoint::{Cp437Grid, DataRef, Grid};
use std::ptr::NonNull;
@ -10,8 +10,7 @@ pub unsafe extern "C" fn sp_cp437_grid_new(
width: usize,
height: usize,
) -> NonNull<Cp437Grid> {
let result = Box::new(Cp437Grid::new(width, height));
NonNull::from(Box::leak(result))
heap_move_nonnull(Cp437Grid::new(width, height))
}
/// Loads a [Cp437Grid] with the specified dimensions from the provided data.
@ -24,7 +23,7 @@ pub unsafe extern "C" fn sp_cp437_grid_load(
let data = unsafe { data.as_slice() };
let grid = Cp437Grid::load(width, height, data);
if let Some(grid) = grid {
Box::leak(Box::new(grid))
heap_move(grid)
} else {
std::ptr::null_mut()
}
@ -35,14 +34,13 @@ pub unsafe extern "C" fn sp_cp437_grid_load(
pub unsafe extern "C" fn sp_cp437_grid_clone(
cp437_grid: NonNull<Cp437Grid>,
) -> NonNull<Cp437Grid> {
let result = Box::new(unsafe { cp437_grid.as_ref().clone() });
NonNull::from(Box::leak(result))
heap_move_nonnull(unsafe { cp437_grid.as_ref().clone() })
}
/// Deallocates a [Cp437Grid].
#[no_mangle]
pub unsafe extern "C" fn sp_cp437_grid_free(cp437_grid: NonNull<Cp437Grid>) {
_ = unsafe { Box::from_raw(cp437_grid.as_ptr()) };
unsafe { heap_drop(cp437_grid) }
}
/// Gets the current value at the specified position.