Skip to content

Commit c660ced

Browse files
committed
Add a GlobalAlloc trait
1 parent 9b06886 commit c660ced

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/libcore/heap.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,36 @@ impl From<AllocErr> for CollectionAllocErr {
404404
}
405405
}
406406

407+
// FIXME: docs
408+
pub unsafe trait GlobalAlloc {
409+
unsafe fn alloc(&self, layout: Layout) -> *mut Void;
410+
411+
unsafe fn dealloc(&self, ptr: *mut Void, layout: Layout);
412+
413+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut Void {
414+
let size = layout.size();
415+
let ptr = self.alloc(layout);
416+
if !ptr.is_null() {
417+
ptr::write_bytes(ptr as *mut u8, 0, size);
418+
}
419+
ptr
420+
}
421+
422+
unsafe fn realloc(&self, ptr: *mut Void, old_layout: Layout, new_size: usize) -> *mut Void {
423+
let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align());
424+
let new_ptr = self.alloc(new_layout);
425+
if !new_ptr.is_null() {
426+
ptr::copy_nonoverlapping(
427+
ptr as *const u8,
428+
new_ptr as *mut u8,
429+
cmp::min(old_layout.size(), new_size),
430+
);
431+
self.dealloc(ptr, old_layout);
432+
}
433+
new_ptr
434+
}
435+
}
436+
407437
/// An implementation of `Alloc` can allocate, reallocate, and
408438
/// deallocate arbitrary blocks of data described via `Layout`.
409439
///

0 commit comments

Comments
 (0)