gear_dlmalloc/
global.rs

1use core::alloc::{GlobalAlloc, Layout};
2use core::ops::{Deref, DerefMut};
3
4use Dlmalloc;
5
6/// An instance of a "global allocator" backed by `Dlmalloc`
7///
8/// This API requires the `global` feature is activated, and this type
9/// implements the `GlobalAlloc` trait in the standard library.
10pub struct GlobalDlmalloc;
11
12unsafe impl GlobalAlloc for GlobalDlmalloc {
13    #[inline]
14    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
15        <Dlmalloc>::malloc(&mut get(), layout.size(), layout.align())
16    }
17
18    #[inline]
19    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
20        <Dlmalloc>::free(&mut get(), ptr, layout.size(), layout.align())
21    }
22
23    #[inline]
24    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
25        <Dlmalloc>::calloc(&mut get(), layout.size(), layout.align())
26    }
27
28    #[inline]
29    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
30        <Dlmalloc>::realloc(&mut get(), ptr, layout.size(), layout.align(), new_size)
31    }
32}
33
34/// Returns malloced size
35pub unsafe fn get_alloced_mem_size() -> usize {
36    <Dlmalloc>::get_alloced_mem_size(&get())
37}
38
39static mut DLMALLOC: Dlmalloc = Dlmalloc(::dlmalloc::DLMALLOC_INIT);
40
41struct Instance;
42
43unsafe fn get() -> Instance {
44    ::sys::acquire_global_lock();
45    Instance
46}
47
48impl Deref for Instance {
49    type Target = Dlmalloc;
50    fn deref(&self) -> &Dlmalloc {
51        unsafe { &DLMALLOC }
52    }
53}
54
55impl DerefMut for Instance {
56    fn deref_mut(&mut self) -> &mut Dlmalloc {
57        unsafe { &mut DLMALLOC }
58    }
59}
60
61impl Drop for Instance {
62    fn drop(&mut self) {
63        ::sys::release_global_lock()
64    }
65}