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