twizzler_rt_abi/alloc.rs
1//! Functions for allocating memory from the runtime.
2
3use core::alloc::Layout;
4
5bitflags::bitflags! {
6 /// Flags for allocation functions.
7 pub struct AllocFlags : crate::bindings::alloc_flags {
8 /// Zero memory. The memory zeroed depends on the function called.
9 const ZERO_MEMORY = crate::bindings::ZERO_MEMORY;
10 }
11}
12
13/// Allocate runtime memory with the given layout and flags. Returns None on allocation failure.
14///
15/// # Flags
16/// - ZERO_MEMORY: Zero the newly-allocated memory before returning it to the user.
17pub fn twz_rt_malloc(layout: Layout, flags: AllocFlags) -> Option<*mut u8> {
18 unsafe {
19 let ptr = crate::bindings::twz_rt_malloc(layout.size(), layout.align(), flags.bits());
20 if ptr.is_null() {
21 None
22 } else {
23 Some(ptr.cast())
24 }
25 }
26}
27
28/// Reallocate runtime memory pointed to by ptr, with a given layout and flags, to new_size. The new
29/// size can be larger or smaller than the original, and may move while maintaining layout
30/// constraints. If the allocation moves, the old memory will be copied over and automatically
31/// freed.
32///
33/// # Safety
34/// Caller must ensure that any no other references to this memory are alive.
35///
36/// # Flags
37/// - ZERO_MEMORY: If the allocation size grows, zero the newly-allocated memory before returning
38/// it to the user. If the allocation size shrinks, zero the old, now unused, part of the memory
39/// before freeing. If the allocation moves, zero the old allocation before freeing.
40pub unsafe fn twz_rt_realloc(
41 ptr: *mut u8,
42 layout: Layout,
43 new_size: usize,
44 flags: AllocFlags,
45) -> Option<*mut u8> {
46 unsafe {
47 let ptr = crate::bindings::twz_rt_realloc(
48 ptr.cast(),
49 layout.size(),
50 layout.align(),
51 new_size,
52 flags.bits(),
53 );
54 if ptr.is_null() {
55 None
56 } else {
57 Some(ptr.cast())
58 }
59 }
60}
61
62/// Deallocate runtime memory pointed to by ptr, with a given layout and flags.
63///
64/// # Safety
65/// Caller must ensure that any no other references to this memory are alive.
66///
67/// # Flags
68/// - ZERO_MEMORY: Zero the old memory before freeing.
69pub unsafe fn twz_rt_dealloc(ptr: *mut u8, layout: Layout, flags: AllocFlags) {
70 unsafe {
71 crate::bindings::twz_rt_dealloc(ptr.cast(), layout.size(), layout.align(), flags.bits())
72 }
73}