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
|
use core::alloc::{GlobalAlloc, Layout};
use core::ops::{Deref, DerefMut};
use Dlmalloc;
pub use sys::enable_alloc_after_fork;
/// An instance of a "global allocator" backed by `Dlmalloc`
///
/// This API requires the `global` feature is activated, and this type
/// implements the `GlobalAlloc` trait in the standard library.
pub struct GlobalDlmalloc;
unsafe impl GlobalAlloc for GlobalDlmalloc {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
<Dlmalloc>::malloc(&mut get(), layout.size(), layout.align())
}
#[inline]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
<Dlmalloc>::free(&mut get(), ptr, layout.size(), layout.align())
}
#[inline]
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
<Dlmalloc>::calloc(&mut get(), layout.size(), layout.align())
}
#[inline]
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
<Dlmalloc>::realloc(&mut get(), ptr, layout.size(), layout.align(), new_size)
}
}
static mut DLMALLOC: Dlmalloc = Dlmalloc::new();
struct Instance;
unsafe fn get() -> Instance {
::sys::acquire_global_lock();
Instance
}
impl Deref for Instance {
type Target = Dlmalloc;
fn deref(&self) -> &Dlmalloc {
unsafe { &DLMALLOC }
}
}
impl DerefMut for Instance {
fn deref_mut(&mut self) -> &mut Dlmalloc {
unsafe { &mut DLMALLOC }
}
}
impl Drop for Instance {
fn drop(&mut self) {
::sys::release_global_lock()
}
}
|