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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Low level memory allocation.
extern crate alloc;
#[cfg(windows)]
use crate::os::windows::alloc::{
    nstd_os_windows_alloc_allocate, nstd_os_windows_alloc_allocate_zeroed,
    nstd_os_windows_alloc_deallocate, nstd_os_windows_alloc_reallocate,
    NSTDWindowsAllocError::{self, *},
};
use crate::{
    core::{
        mem::nstd_core_mem_copy,
        ptr::raw::{nstd_core_ptr_raw_dangling_mut, MAX_ALIGN},
    },
    NSTDAny, NSTDAnyMut, NSTDUInt, NSTD_NULL,
};
use alloc::alloc::Layout;
use cfg_if::cfg_if;
use core::{
    marker::PhantomData,
    ops::{Deref, DerefMut},
    ptr::addr_of,
};
use nstdapi::nstdapi;

/// An FFI safe [Box] variant for `nstd`.
#[repr(transparent)]
#[allow(dead_code)]
pub(crate) struct CBox<T>(NSTDAnyMut, PhantomData<T>);
#[allow(dead_code)]
impl<T> CBox<T> {
    /// Creates a new heap allocated [CBox] object.
    pub(crate) fn new(value: T) -> Option<Self> {
        let size = core::mem::size_of::<T>();
        match size {
            #[allow(unused_unsafe)]
            // SAFETY: This operation is safe.
            0 => unsafe { Some(Self(nstd_core_ptr_raw_dangling_mut(), Default::default())) },
            // SAFETY: `size` is greater than 0.
            _ => match unsafe { nstd_alloc_allocate(size) } {
                NSTD_NULL => None,
                mem => {
                    // SAFETY: `mem` is a non-null pointer to `size` uninitialized bytes.
                    unsafe { nstd_core_mem_copy(mem as _, addr_of!(value) as _, size) };
                    core::mem::forget(value);
                    Some(Self(mem, Default::default()))
                }
            },
        }
    }

    /// Moves a [CBox] value onto the stack.
    pub(crate) fn into_inner(mut self) -> T {
        // SAFETY: `self.0` points to a valid object of type `T`.
        let value = unsafe { (self.0 as *const T).read() };
        let size = core::mem::size_of::<T>();
        if size > 0 {
            // SAFETY:
            // - `self.0` points to a valid object of type `T`.
            // - `size` is greater than 0.
            unsafe { nstd_alloc_deallocate(&mut self.0, size) };
        }
        core::mem::forget(self);
        value
    }
}
impl<T> Deref for CBox<T> {
    /// [CBox]'s dereference target.
    type Target = T;

    /// Immutably dereferences a [CBox].
    #[inline]
    fn deref(&self) -> &Self::Target {
        // SAFETY: `self.0` points to a valid object of type `T`.
        unsafe { &*(self.0 as *const _) }
    }
}
impl<T> DerefMut for CBox<T> {
    /// Mutably dereferences a [CBox].
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: `self.0` points to a valid object of type `T`.
        unsafe { &mut *(self.0 as *mut _) }
    }
}
impl<T> Drop for CBox<T> {
    /// [CBox]'s destructor.
    fn drop(&mut self) {
        // SAFETY:
        // - `self.0` points to a valid object of type `T`.
        // - `size` is greater than 0.
        unsafe {
            drop(self.0.cast::<T>().read());
            let size = core::mem::size_of::<T>();
            if size > 0 {
                nstd_alloc_deallocate(&mut (self.0 as _), size);
            }
        }
    }
}

/// Describes an error returned from allocation functions.
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum NSTDAllocError {
    /// No error occurred.
    NSTD_ALLOC_ERROR_NONE,
    /// Allocating or reallocating failed.
    NSTD_ALLOC_ERROR_OUT_OF_MEMORY,
    /// Deallocating memory failed.
    NSTD_ALLOC_ERROR_MEMORY_NOT_FOUND,
    /// Getting a handle to a heap failed.
    NSTD_ALLOC_ERROR_HEAP_NOT_FOUND,
    /// A heap is invalid.
    NSTD_ALLOC_ERROR_INVALID_HEAP,
    /// An allocation function received input parameters that resulted in an invalid memory layout.
    NSTD_ALLOC_ERROR_INVALID_LAYOUT,
}
#[cfg(windows)]
impl From<NSTDWindowsAllocError> for NSTDAllocError {
    /// Converts an [NSTDWindowsAllocError] into an [NSTDAllocError].
    fn from(err: NSTDWindowsAllocError) -> Self {
        match err {
            NSTD_WINDOWS_ALLOC_ERROR_NONE => Self::NSTD_ALLOC_ERROR_NONE,
            NSTD_WINDOWS_ALLOC_ERROR_OUT_OF_MEMORY => Self::NSTD_ALLOC_ERROR_OUT_OF_MEMORY,
            NSTD_WINDOWS_ALLOC_ERROR_MEMORY_NOT_FOUND => Self::NSTD_ALLOC_ERROR_MEMORY_NOT_FOUND,
            NSTD_WINDOWS_ALLOC_ERROR_HEAP_NOT_FOUND => Self::NSTD_ALLOC_ERROR_HEAP_NOT_FOUND,
            NSTD_WINDOWS_ALLOC_ERROR_INVALID_HEAP => Self::NSTD_ALLOC_ERROR_INVALID_HEAP,
            NSTD_WINDOWS_ALLOC_ERROR_INVALID_LAYOUT => Self::NSTD_ALLOC_ERROR_INVALID_LAYOUT,
        }
    }
}

/// A structure of function pointers making up an allocator VTable.
#[nstdapi]
#[derive(Clone, Copy)]
pub struct NSTDAllocator {
    /// An opaque pointer to the allocator's state.
    pub state: NSTDAny,
    /// Allocates a contiguous sequence of `size` bytes in memory.
    ///
    /// If allocation fails, a null pointer is returned.
    ///
    /// If allocation succeeds, this returns a pointer that is suitably aligned for any type with
    /// [fundamental alignment](https://en.cppreference.com/w/c/language/object#Alignment), i.e.,
    /// the returned pointer will be suitably aligned for
    /// [max_align_t](https://en.cppreference.com/w/c/types/max_align_t).
    ///
    /// Allocation will fail if `size` is greater than `NSTDInt`'s max value.
    ///
    /// # Parameters:
    ///
    /// - `NSTDUInt size` - The number of bytes to allocate.
    ///
    /// # Returns
    ///
    /// `NSTDAnyMut ptr` - A pointer to the allocated memory, null on error.
    ///
    /// # Safety
    ///
    /// - Behavior is undefined if `size` is zero.
    ///
    /// - The new memory buffer should be considered uninitialized.
    pub allocate: unsafe extern "C" fn(NSTDAny, NSTDUInt) -> NSTDAnyMut,
    /// Allocates a contiguous sequence of `size` bytes in memory.
    ///
    /// The initialized memory is zero-initialized.
    ///
    /// If allocation fails, a null pointer is returned.
    ///
    /// If allocation succeeds, this returns a pointer that is suitably aligned for any type with
    /// [fundamental alignment](https://en.cppreference.com/w/c/language/object#Alignment), i.e.,
    /// the returned pointer will be suitably aligned for
    /// [max_align_t](https://en.cppreference.com/w/c/types/max_align_t).
    ///
    /// Allocation will fail if `size` is greater than `NSTDInt`'s max value.
    ///
    /// # Parameters:
    ///
    /// - `NSTDUInt size` - The number of bytes to allocate.
    ///
    /// # Returns
    ///
    /// `NSTDAnyMut ptr` - A pointer to the allocated memory, null on error.
    ///
    /// # Safety
    ///
    /// - Behavior is undefined if `size` is zero.
    ///
    /// - The new memory buffer should be considered uninitialized.
    pub allocate_zeroed: unsafe extern "C" fn(NSTDAny, NSTDUInt) -> NSTDAnyMut,
    /// Reallocates memory that was previously allocated by this allocator.
    ///
    /// Reallocation will fail if `new_size` is greater than `NSTDInt`'s max value.
    ///
    /// On successful reallocation, `ptr` will point to the new memory location and
    /// `NSTD_ALLOC_ERROR_NONE` will be returned. If this is not the case and reallocation fails,
    /// the pointer will remain untouched and the appropriate error is returned.
    ///
    /// # Parameters:
    ///
    /// - `NSTDAnyMut *ptr` - A pointer to the allocated memory.
    ///
    /// - `NSTDUInt size` - The number of bytes currently allocated.
    ///
    /// - `NSTDUInt new_size` - The number of bytes to reallocate.
    ///
    /// # Returns
    ///
    /// `NSTDAllocError errc` - The allocation operation error code.
    ///
    /// # Safety
    ///
    /// - Behavior is undefined if `new_size` is zero.
    ///
    /// - Behavior is undefined if `ptr` is not a value returned by this allocator.
    ///
    /// - `size` must be the same value that was used to allocate the memory buffer.
    pub reallocate:
        unsafe extern "C" fn(NSTDAny, &mut NSTDAnyMut, NSTDUInt, NSTDUInt) -> NSTDAllocError,
    /// Deallocates memory that was previously allocated by this allocator.
    ///
    /// On successful deallocation, `ptr` will be set to null and `NSTD_ALLOC_ERROR_NONE` will be
    /// returned. If this is not the case and deallocation fails, the pointer will remain untouched
    /// and the appropriate error is returned.
    ///
    /// # Parameters:
    ///
    /// - `NSTDAnyMut *ptr` - A pointer to the allocated memory, once freed the pointer is set to
    /// null.
    ///
    /// - `NSTDUInt size` - The number of bytes currently allocated.
    ///
    /// # Returns
    ///
    /// `NSTDAllocError errc` - The allocation operation error code.
    ///
    /// # Safety
    ///
    /// - Behavior is undefined if `ptr` is not a value returned by this allocator.
    ///
    /// - `size` must be the same value that was used to allocate the memory buffer.
    pub deallocate: unsafe extern "C" fn(NSTDAny, &mut NSTDAnyMut, NSTDUInt) -> NSTDAllocError,
}
/// # Safety
///
/// The allocator's state must be able to be safely *shared* between threads.
// SAFETY: The user guarantees that the state is thread-safe.
unsafe impl Send for NSTDAllocator {}
/// # Safety
///
/// The allocator's state must be able to be safely shared between threads.
// SAFETY: The user guarantees that the state is thread-safe.
unsafe impl Sync for NSTDAllocator {}

/// Forwards an `NSTD_ALLOCATOR`'s `allocate` call to `nstd_alloc_allocate`.
#[inline]
unsafe extern "C" fn allocate(_: NSTDAny, size: NSTDUInt) -> NSTDAnyMut {
    nstd_alloc_allocate(size)
}

/// Forwards an `NSTD_ALLOCATOR`'s `allocate_zeroed` call to `nstd_alloc_allocate_zeroed`.
#[inline]
unsafe extern "C" fn allocate_zeroed(_: NSTDAny, size: NSTDUInt) -> NSTDAnyMut {
    nstd_alloc_allocate_zeroed(size)
}

/// Forwards an `NSTD_ALLOCATOR`'s `reallocate` call to `nstd_alloc_reallocate`.
#[inline]
unsafe extern "C" fn reallocate(
    _: NSTDAny,
    ptr: &mut NSTDAnyMut,
    size: NSTDUInt,
    new_size: NSTDUInt,
) -> NSTDAllocError {
    nstd_alloc_reallocate(ptr, size, new_size)
}

/// Forwards an `NSTD_ALLOCATOR`'s `deallocate` call to `nstd_alloc_deallocate`.
#[inline]
unsafe extern "C" fn deallocate(
    _: NSTDAny,
    ptr: &mut NSTDAnyMut,
    size: NSTDUInt,
) -> NSTDAllocError {
    nstd_alloc_deallocate(ptr, size)
}

/// `nstd`'s default allocator.
#[nstdapi]
pub static NSTD_ALLOCATOR: NSTDAllocator = NSTDAllocator {
    state: NSTD_NULL,
    allocate,
    allocate_zeroed,
    reallocate,
    deallocate,
};

/// The `NSTDAllocator`'s `allocate` function.
#[inline]
unsafe extern "C" fn rust_allocate(_: NSTDAny, size: NSTDUInt) -> NSTDAnyMut {
    if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
        return alloc::alloc::alloc(layout).cast();
    }
    NSTD_NULL
}

/// The `NSTDAllocator`'s `allocate_zeroed` function.
#[inline]
unsafe extern "C" fn rust_allocate_zeroed(_: NSTDAny, size: NSTDUInt) -> NSTDAnyMut {
    if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
        return alloc::alloc::alloc_zeroed(layout).cast();
    }
    NSTD_NULL
}

/// The `NSTDAllocator`'s `reallocate` function.
unsafe extern "C" fn rust_reallocate(
    _: NSTDAny,
    ptr: &mut NSTDAnyMut,
    size: NSTDUInt,
    new_size: NSTDUInt,
) -> NSTDAllocError {
    if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
        let new_mem = alloc::alloc::realloc((*ptr).cast(), layout, new_size);
        if new_mem.is_null() {
            return NSTDAllocError::NSTD_ALLOC_ERROR_OUT_OF_MEMORY;
        }
        *ptr = new_mem.cast();
        return NSTDAllocError::NSTD_ALLOC_ERROR_NONE;
    }
    NSTDAllocError::NSTD_ALLOC_ERROR_INVALID_LAYOUT
}

/// The `NSTDAllocator`'s `deallocate` function.
unsafe extern "C" fn rust_deallocate(
    _: NSTDAny,
    ptr: &mut NSTDAnyMut,
    size: NSTDUInt,
) -> NSTDAllocError {
    if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
        alloc::alloc::dealloc((*ptr).cast(), layout);
        *ptr = NSTD_NULL;
        return NSTDAllocError::NSTD_ALLOC_ERROR_NONE;
    }
    NSTDAllocError::NSTD_ALLOC_ERROR_INVALID_LAYOUT
}

/// Rust's [Global] [NSTDAllocator].
#[allow(dead_code)]
pub(crate) static GLOBAL_ALLOCATOR: NSTDAllocator = NSTDAllocator {
    state: NSTD_NULL,
    allocate: rust_allocate,
    allocate_zeroed: rust_allocate_zeroed,
    reallocate: rust_reallocate,
    deallocate: rust_deallocate,
};

/// Allocates a block of memory on the heap.
/// The number of bytes to be allocated is specified by `size`.
///
/// # Parameters:
///
/// - `NSTDUInt size` - The number of bytes to allocate on the heap.
///
/// # Returns
///
/// `NSTDAnyMut ptr` - A pointer to the allocated memory, null on error.
///
/// # Safety
///
/// - Behavior is undefined if `size` is zero.
///
/// - The new memory buffer should be considered uninitialized.
///
/// # Example
///
/// ```
/// use nstd_sys::alloc::{nstd_alloc_allocate, nstd_alloc_deallocate};
///
/// unsafe {
///     let mut mem = nstd_alloc_allocate(32);
///     assert!(!mem.is_null());
///     nstd_alloc_deallocate(&mut mem, 32);
/// }
/// ```
#[inline]
#[nstdapi]
pub unsafe fn nstd_alloc_allocate(size: NSTDUInt) -> NSTDAnyMut {
    cfg_if! {
        if #[cfg(any(
            unix,
            any(target_env = "wasi", target_os = "wasi"),
            target_os = "solid_asp3"
        ))] {
            use crate::NSTD_INT_MAX;
            match size <= NSTD_INT_MAX as _ {
                true => libc::malloc(size),
                false => NSTD_NULL,
            }
        } else if #[cfg(windows)] {
            nstd_os_windows_alloc_allocate(size)
        } else {
            if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
                return alloc::alloc::alloc(layout).cast();
            }
            NSTD_NULL
        }
    }
}

/// Allocates a block of zero-initialized memory on the heap.
///
/// # Parameters:
///
/// - `NSTDUInt size` - The number of bytes to allocate on the heap.
///
/// # Returns
///
/// `NSTDAnyMut ptr` - A pointer to the allocated memory, null on error.
///
/// # Safety
///
/// Behavior is undefined if `size` is zero.
///
/// # Example
///
/// ```
/// use nstd_sys::alloc::{nstd_alloc_allocate_zeroed, nstd_alloc_deallocate};
///
/// const SIZE: usize = core::mem::size_of::<[i16; 16]>();
///
/// unsafe {
///     let mut mem = nstd_alloc_allocate_zeroed(SIZE);
///     assert!(!mem.is_null());
///     assert!(*mem.cast::<[i16; 16]>() == [0i16; 16]);
///
///     nstd_alloc_deallocate(&mut mem, SIZE);
/// }
/// ```
#[inline]
#[nstdapi]
pub unsafe fn nstd_alloc_allocate_zeroed(size: NSTDUInt) -> NSTDAnyMut {
    cfg_if! {
        if #[cfg(any(
            unix,
            any(target_env = "wasi", target_os = "wasi"),
            target_os = "solid_asp3"
        ))] {
            use crate::NSTD_INT_MAX;
            match size <= NSTD_INT_MAX as _ {
                true => libc::calloc(size, 1),
                false => NSTD_NULL,
            }
        } else if #[cfg(windows)] {
            nstd_os_windows_alloc_allocate_zeroed(size)
        } else {
            if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
                return alloc::alloc::alloc_zeroed(layout).cast();
            }
            NSTD_NULL
        }
    }
}

/// Reallocates a block of memory previously allocated by `nstd_alloc_allocate[_zeroed]`.
///
/// If everything goes right, the pointer will point to the new memory location and
/// `NSTD_ALLOC_ERROR_NONE` will be returned. If this is not the case and allocation fails, the
/// pointer will remain untouched and the appropriate error is returned.
///
/// # Parameters:
///
/// - `NSTDAnyMut *ptr` - A pointer to the allocated memory.
///
/// - `NSTDUInt size` - The number of bytes currently allocated.
///
/// - `NSTDUInt new_size` - The number of bytes to reallocate.
///
/// # Returns
///
/// `NSTDAllocError errc` - The allocation operation error code.
///
/// # Safety
///
/// - Behavior is undefined if `new_size` is zero.
///
/// - Behavior is undefined if `ptr` is not a value returned by `nstd_alloc_allocate[_zeroed]`.
///
/// - `size` must be the same value that was used to allocate the memory buffer.
///
/// # Example
///
/// ```
/// use nstd_sys::alloc::{
///     nstd_alloc_allocate_zeroed, nstd_alloc_deallocate, nstd_alloc_reallocate,
///     NSTDAllocError::NSTD_ALLOC_ERROR_NONE,
/// };
///
/// const SIZE: usize = core::mem::size_of::<[u64; 64]>();
///
/// unsafe {
///     let mut mem = nstd_alloc_allocate_zeroed(SIZE);
///     assert!(!mem.is_null());
///     assert!(*mem.cast::<[u64; 64]>() == [0u64; 64]);
///
///     assert!(nstd_alloc_reallocate(&mut mem, SIZE, SIZE / 2) == NSTD_ALLOC_ERROR_NONE);
///     assert!(*mem.cast::<[u64; 32]>() == [0u64; 32]);
///
///     nstd_alloc_deallocate(&mut mem, SIZE);
/// }
/// ```
#[nstdapi]
#[cfg_attr(windows, inline)]
#[allow(unused_variables)]
pub unsafe fn nstd_alloc_reallocate(
    ptr: &mut NSTDAnyMut,
    size: NSTDUInt,
    new_size: NSTDUInt,
) -> NSTDAllocError {
    cfg_if! {
        if #[cfg(any(
            unix,
            any(target_env = "wasi", target_os = "wasi"),
            target_os = "solid_asp3"
        ))] {
            use crate::NSTD_INT_MAX;
            if new_size > NSTD_INT_MAX as _ {
                return NSTDAllocError::NSTD_ALLOC_ERROR_INVALID_LAYOUT;
            }
            let new_mem = libc::realloc(*ptr, new_size);
            if new_mem.is_null() {
                return NSTDAllocError::NSTD_ALLOC_ERROR_OUT_OF_MEMORY;
            }
            *ptr = new_mem;
            NSTDAllocError::NSTD_ALLOC_ERROR_NONE
        } else if #[cfg(windows)] {
            nstd_os_windows_alloc_reallocate(ptr, new_size).into()
        } else {
            if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
                let new_mem = alloc::alloc::realloc((*ptr).cast(), layout, new_size);
                if new_mem.is_null() {
                    return NSTDAllocError::NSTD_ALLOC_ERROR_OUT_OF_MEMORY;
                }
                *ptr = new_mem.cast();
                return NSTDAllocError::NSTD_ALLOC_ERROR_NONE;
            }
            NSTDAllocError::NSTD_ALLOC_ERROR_INVALID_LAYOUT
        }
    }
}

/// Deallocates a block of memory previously allocated by `nstd_alloc_allocate[_zeroed]`.
///
/// # Parameters:
///
/// - `NSTDAnyMut *ptr` - A pointer to the allocated memory, once freed the pointer is set to null.
///
/// - `NSTDUInt size` - The number of bytes to free.
///
/// # Returns
///
/// `NSTDAllocError errc` - The allocation operation error code.
///
/// # Safety
///
/// - Behavior is undefined if `ptr` is not a value returned by `nstd_alloc_allocate[_zeroed]`.
///
/// - `size` must be the same value that was used to allocate the memory buffer.
///
/// # Example
///
/// ```
/// use nstd_sys::alloc::{nstd_alloc_allocate, nstd_alloc_deallocate};
///
/// unsafe {
///     let mut mem = nstd_alloc_allocate(24);
///     assert!(!mem.is_null());
///     nstd_alloc_deallocate(&mut mem, 24);
/// }
/// ```
#[inline]
#[nstdapi]
#[allow(unused_variables)]
pub unsafe fn nstd_alloc_deallocate(ptr: &mut NSTDAnyMut, size: NSTDUInt) -> NSTDAllocError {
    cfg_if! {
        if #[cfg(any(
            unix,
            any(target_env = "wasi", target_os = "wasi"),
            target_os = "solid_asp3"
        ))] {
            libc::free(*ptr);
            *ptr = NSTD_NULL;
            NSTDAllocError::NSTD_ALLOC_ERROR_NONE
        } else if #[cfg(windows)] {
            nstd_os_windows_alloc_deallocate(ptr).into()
        } else {
            if let Ok(layout) = Layout::from_size_align(size, MAX_ALIGN) {
                alloc::alloc::dealloc((*ptr).cast(), layout);
                *ptr = NSTD_NULL;
                return NSTDAllocError::NSTD_ALLOC_ERROR_NONE;
            }
            NSTDAllocError::NSTD_ALLOC_ERROR_INVALID_LAYOUT
        }
    }
}