1use std::alloc::{AllocError, Allocator};
21use std::alloc::{GlobalAlloc, Layout};
22
23use crate::mem::cast_to_nonnull;
24use std::ptr::NonNull;
25
26#[cfg(feature = "fast_allocator")]
27use mimalloc::MiMalloc;
28
29#[cfg(feature = "fast_allocator")]
30static mut SAND: MiMalloc = MiMalloc;
31
32#[cfg(not(feature = "fast_allocator"))]
33use std::alloc::System;
34
35
36#[cfg(not(feature = "fast_allocator"))]
37static mut SAND: System = System;
38
39#[inline(always)]
40pub unsafe fn direct_alloc(layout: Layout) -> *mut u8 {
41 SAND.alloc(layout)
42}
43
44#[inline(always)]
45pub unsafe fn direct_dealloc(ptr: *mut u8, layout: Layout) {
46 SAND.dealloc(ptr, layout)
47}
48
49pub struct DirectAllocator;
50
51unsafe impl Allocator for DirectAllocator {
52 #[inline(always)]
53 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
54 let ptr = unsafe { direct_alloc(layout) };
55 let slice = unsafe { std::slice::from_raw_parts_mut(ptr, layout.size()) };
56 Ok(cast_to_nonnull::<[u8]>(slice))
57 }
58 #[inline(always)]
59 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
60 direct_dealloc(ptr.as_ptr(), layout);
61 }
62}
63
64pub static DIRECT_ALLOCATOR: DirectAllocator = DirectAllocator;
65