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::{Header, Packet, TypedCommand};
use std::ptr::NonNull;
@ -12,7 +12,7 @@ pub unsafe extern "C" fn sp_packet_from_command(
) -> *mut Packet {
let command = unsafe { *Box::from_raw(command.as_ptr()) };
if let Ok(packet) = command.try_into() {
Box::leak(Box::new(packet))
heap_move(packet)
} else {
std::ptr::null_mut()
}
@ -26,7 +26,7 @@ pub unsafe extern "C" fn sp_packet_try_load(data: ByteSlice) -> *mut Packet {
let data = unsafe { data.as_slice() };
match servicepoint::Packet::try_from(data) {
Err(_) => std::ptr::null_mut(),
Ok(packet) => Box::into_raw(Box::new(packet)),
Ok(packet) => heap_move(packet),
}
}
@ -45,8 +45,7 @@ pub unsafe extern "C" fn sp_packet_from_parts(
Vec::from(payload)
};
let packet = Box::new(Packet { header, payload });
NonNull::from(Box::leak(packet))
heap_move_nonnull(Packet { header, payload })
}
/// Returns a pointer to the header field of the provided packet.
@ -100,12 +99,11 @@ pub unsafe extern "C" fn sp_packet_serialize_to(
pub unsafe extern "C" fn sp_packet_clone(
packet: NonNull<Packet>,
) -> NonNull<Packet> {
let result = Box::new(unsafe { packet.as_ref().clone() });
NonNull::from(Box::leak(result))
heap_move_nonnull(unsafe { packet.as_ref().clone() })
}
/// Deallocates a [Packet].
#[no_mangle]
pub unsafe extern "C" fn sp_packet_free(packet: NonNull<Packet>) {
_ = unsafe { Box::from_raw(packet.as_ptr()) }
unsafe { heap_drop(packet) }
}