1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//! A pointer type for single value heap allocation.
use crate::{
    alloc::{
        nstd_alloc_allocate, nstd_alloc_allocate_zeroed, nstd_alloc_deallocate,
        NSTDAllocError::NSTD_ALLOC_ERROR_NONE,
    },
    core::mem::nstd_core_mem_copy,
    NSTDAny, NSTDAnyMut, NSTDUInt,
};

/// A pointer type for single value heap allocation.
#[repr(C)]
#[derive(Debug, Hash, PartialEq, Eq)]
pub struct NSTDHeapPtr {
    /// A raw pointer to the value on the heap.
    ptr: NSTDAnyMut,
    /// The size of the object in bytes.
    size: NSTDUInt,
}
impl Drop for NSTDHeapPtr {
    /// [NSTDHeapPtr]'s destructor.
    ///
    /// # Panics
    ///
    /// Panics if deallocating fails.
    #[inline]
    fn drop(&mut self) {
        // SAFETY: Heap pointers are always non-null.
        unsafe {
            assert!(nstd_alloc_deallocate(&mut self.ptr, self.size) == NSTD_ALLOC_ERROR_NONE);
        }
    }
}

/// Creates a new initialized heap allocated object.
///
/// # Parameters:
///
/// - `NSTDUInt element_size` - The size (in bytes) of the heap object.
///
/// - `NSTDAny init` - A pointer to the object to initialize the heap object with.
///
/// # Returns
///
/// `NSTDHeapPtr hptr` - The new heap allocated object.
///
/// # Panics
///
/// This function will panic if either `element_size` is zero, or allocation fails.
///
/// # Safety
///
/// `init` must be a pointer to a value that is valid for reads of `element_size` bytes.
///
/// # Example
///
/// ```
/// use core::ptr::addr_of;
/// use nstd_sys::heap_ptr::nstd_heap_ptr_new;
///
/// const SIZE: usize = core::mem::size_of::<char>();
///
/// let v = '🦀';
/// let hptr = unsafe { nstd_heap_ptr_new(SIZE, addr_of!(v).cast()) };
/// ```
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_heap_ptr_new(element_size: NSTDUInt, init: NSTDAny) -> NSTDHeapPtr {
    assert!(element_size != 0);
    let mem = nstd_alloc_allocate(element_size);
    assert!(!mem.is_null());
    nstd_core_mem_copy(mem.cast(), init.cast(), element_size);
    NSTDHeapPtr {
        ptr: mem,
        size: element_size,
    }
}

/// Creates a new zero-initialized heap allocated object.
///
/// # Parameters:
///
/// - `NSTDUInt element_size` - The size (in bytes) of the heap object.
///
/// # Returns
///
/// `NSTDHeapPtr hptr` - The new heap allocated object.
///
/// # Panics
///
/// This function will panic if either `element_size` is zero, or allocation fails.
///
/// # Example
///
/// ```
/// use nstd_sys::heap_ptr::{nstd_heap_ptr_get, nstd_heap_ptr_new_zeroed};
///
/// const SIZE: usize = core::mem::size_of::<u64>();
///
/// unsafe {
///     let hptr = nstd_heap_ptr_new_zeroed(SIZE);
///     assert!(*nstd_heap_ptr_get(&hptr).cast::<u64>() == 0);
/// }
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_heap_ptr_new_zeroed(element_size: NSTDUInt) -> NSTDHeapPtr {
    assert!(element_size != 0);
    // SAFETY: `element_size` is not 0.
    let mem = unsafe { nstd_alloc_allocate_zeroed(element_size) };
    assert!(!mem.is_null());
    NSTDHeapPtr {
        ptr: mem,
        size: element_size,
    }
}

/// Creates a clone of a heap allocated object.
///
/// # Parameters:
///
/// - `const NSTDHeapPtr *hptr` - The heap pointer.
///
/// # Returns
///
/// `NSTDHeapPtr cloned` - A new clone of the original heap object.
///
/// # Panics
///
/// This function will panic if allocation fails.
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_heap_ptr_clone(hptr: &NSTDHeapPtr) -> NSTDHeapPtr {
    let size = nstd_heap_ptr_size(hptr);
    // SAFETY: `size` is not 0.
    let mem = unsafe { nstd_alloc_allocate(size) };
    assert!(!mem.is_null());
    // SAFETY: Both pointers are non-null.
    unsafe { nstd_core_mem_copy(mem.cast(), hptr.ptr.cast(), size) };
    NSTDHeapPtr { ptr: mem, size }
}

/// Returns the size of the heap allocated object.
///
/// # Parameters:
///
/// - `const NSTDHeapPtr *hptr` - The heap pointer.
///
/// # Returns
///
/// `NSTDUInt size` - The size of the heap allocated object.
///
/// # Example
///
/// ```
/// use nstd_sys::heap_ptr::{nstd_heap_ptr_new_zeroed, nstd_heap_ptr_size};
///
/// const SIZE: usize = core::mem::size_of::<i32>();
///
/// let hptr = unsafe { nstd_heap_ptr_new_zeroed(SIZE) };
/// assert!(nstd_heap_ptr_size(&hptr) == SIZE);
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_heap_ptr_size(hptr: &NSTDHeapPtr) -> NSTDUInt {
    hptr.size
}

/// Returns an immutable raw pointer to the object on the heap.
///
/// # Parameters:
///
/// - `const NSTDHeapPtr *hptr` - The heap pointer.
///
/// # Returns
///
/// `NSTDAny ptr` - A raw pointer to the object on the heap.
///
/// # Example
///
/// ```
/// use core::ptr::addr_of;
/// use nstd_sys::heap_ptr::{nstd_heap_ptr_get, nstd_heap_ptr_new};
///
/// const SIZE: usize = core::mem::size_of::<i128>();
///
/// unsafe {
///     let v = -46923i128;
///     let hptr = nstd_heap_ptr_new(SIZE, addr_of!(v).cast());
///     assert!(*nstd_heap_ptr_get(&hptr).cast::<i128>() == v);
/// }
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_heap_ptr_get(hptr: &NSTDHeapPtr) -> NSTDAny {
    hptr.ptr
}

/// Returns a raw pointer to the object on the heap.
///
/// # Parameters:
///
/// - `NSTDHeapPtr *hptr` - The heap pointer.
///
/// # Returns
///
/// `NSTDAnyMut ptr` - A raw pointer to the object on the heap.
///
/// # Example
///
/// ```
/// use core::ptr::addr_of;
/// use nstd_sys::heap_ptr::{nstd_heap_ptr_get_mut, nstd_heap_ptr_new};
///
/// const SIZE: usize = core::mem::size_of::<i128>();
///
/// unsafe {
///     let v = 32964i128;
///     let mut hptr = nstd_heap_ptr_new(SIZE, addr_of!(v).cast());
///     let hv = nstd_heap_ptr_get_mut(&mut hptr).cast::<i128>();
///     assert!(*hv == v);
///     *hv = -46923;
///     assert!(*hv != v);
/// }
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_heap_ptr_get_mut(hptr: &mut NSTDHeapPtr) -> NSTDAnyMut {
    hptr.ptr
}

/// Frees an instance of `NSTDHeapPtr`.
///
/// # Parameters:
///
/// - `NSTDHeapPtr hptr` - A pointer to the heap object.
///
/// # Panics
///
/// Panics if freeing the heap memory fails.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
#[allow(unused_variables)]
pub extern "C" fn nstd_heap_ptr_free(hptr: NSTDHeapPtr) {}