1 #![feature(allocator_api, alloc)]
2 #![cfg_attr(target_arch = "wasm32", feature(link_llvm_intrinsics))]
7 use alloc
::heap
::{Alloc, Layout, AllocErr}
;
11 pub use self::global
::GlobalDlmalloc
;
16 pub struct Dlmalloc(dlmalloc
::Dlmalloc
);
18 #[cfg(target_arch = "wasm32")]
22 #[cfg(target_os = "macos")]
26 #[cfg(target_os = "linux")]
31 pub fn new() -> Dlmalloc
{
32 Dlmalloc(dlmalloc
::Dlmalloc
::new())
36 unsafe impl Alloc
for Dlmalloc
{
38 unsafe fn alloc(&mut self, layout
: Layout
) -> Result
<*mut u8, AllocErr
> {
39 let ptr
= if layout
.align() <= self.0.malloc_alignment() {
40 self.0.malloc(layout
.size())
42 self.0.memalign(layout
.align(), layout
.size())
45 Err(AllocErr
::Exhausted { request: layout }
)
52 unsafe fn alloc_zeroed(&mut self, layout
: Layout
)
53 -> Result
<*mut u8, AllocErr
>
55 let size
= layout
.size();
56 let ptr
= self.alloc(layout
)?
;
57 if self.0.calloc_must_clear(ptr
) {
58 ptr
::write_bytes(ptr
, 0, size
);
64 unsafe fn dealloc(&mut self, ptr
: *mut u8, layout
: Layout
) {
70 unsafe fn realloc(&mut self,
73 new_layout
: Layout
) -> Result
<*mut u8, AllocErr
> {
74 if old_layout
.align() != new_layout
.align() {
75 return Err(AllocErr
::Unsupported
{
76 details
: "cannot change alignment on `realloc`",
80 if new_layout
.align() <= self.0.malloc_alignment() {
81 let ptr
= self.0.realloc(ptr
, new_layout
.size());
85 Err(AllocErr
::Exhausted { request: new_layout }
)
88 let res
= self.alloc(new_layout
.clone());
89 if let Ok(new_ptr
) = res
{
90 let size
= cmp
::min(old_layout
.size(), new_layout
.size());
91 ptr
::copy_nonoverlapping(ptr
, new_ptr
, size
);
92 self.dealloc(ptr
, old_layout
);
98 // fn oom(&mut self, err: AllocErr) -> ! {
103 // fn usable_size(&self, layout: &Layout) -> (usize, usize) {
104 // (&self).usable_size(layout)
108 // unsafe fn alloc_excess(&mut self, layout: Layout) -> Result<Excess, AllocErr> {
109 // (&*self).alloc_excess(layout)
113 // unsafe fn realloc_excess(&mut self,
116 // new_layout: Layout) -> Result<Excess, AllocErr> {
117 // (&*self).realloc_excess(ptr, layout, new_layout)
121 // unsafe fn grow_in_place(&mut self,
124 // new_layout: Layout) -> Result<(), CannotReallocInPlace> {
125 // (&*self).grow_in_place(ptr, layout, new_layout)
129 // unsafe fn shrink_in_place(&mut self,
132 // new_layout: Layout) -> Result<(), CannotReallocInPlace> {
133 // (&*self).shrink_in_place(ptr, layout, new_layout)
137 // unsafe impl<'a> Alloc for &'a Dlmalloc {
139 // unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
144 // // unsafe fn alloc_zeroed(&mut self, layout: Layout)
145 // // -> Result<*mut u8, AllocErr>
151 // unsafe fn dealloc(&mut self, ptr: *mut u8, layout: Layout) {
156 // // unsafe fn realloc(&mut self,
158 // // old_layout: Layout,
159 // // new_layout: Layout) -> Result<*mut u8, AllocErr> {
163 // fn oom(&mut self, err: AllocErr) -> ! {