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
use std::alloc::{GlobalAlloc, Layout};
use std::sync::atomic::{AtomicPtr, Ordering};
type AllocFn = unsafe fn(Layout) -> *mut u8;
type DeallocFn = unsafe fn(*mut u8, Layout);
#[repr(C)]
pub struct HostAllocatorPtr {
pub alloc_fn: AllocFn,
pub dealloc_fn: DeallocFn,
}
pub struct HostAllocator {
alloc_fn: AtomicPtr<AllocFn>,
dealloc_fn: AtomicPtr<DeallocFn>,
}
impl HostAllocator {
pub const fn new() -> Self {
HostAllocator {
alloc_fn: AtomicPtr::new(std::ptr::null_mut()),
dealloc_fn: AtomicPtr::new(std::ptr::null_mut()),
}
}
pub fn set_allocator(&self, allocator: HostAllocatorPtr) {
self.alloc_fn
.store(allocator.alloc_fn as *mut _, Ordering::SeqCst);
self.dealloc_fn
.store(allocator.dealloc_fn as *mut _, Ordering::SeqCst);
}
}
unsafe impl GlobalAlloc for HostAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
(*self.alloc_fn.load(Ordering::Relaxed))(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
(*self.dealloc_fn.load(Ordering::Relaxed))(ptr, layout)
}
}