about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorSimon Sapin <simon.sapin@exyr.org>2018-04-03 14:07:06 +0200
committerSimon Sapin <simon.sapin@exyr.org>2018-04-12 22:52:47 +0200
commitc660cedc02e125fe47d90075837c5d8adeb4c097 (patch)
treef9081bf217426750630b0f601740c0d41f4bc886 /src
parent9b068867f0ac0851ff0b23381e5b1b1c09b4002e (diff)
downloadrust-c660cedc02e125fe47d90075837c5d8adeb4c097.tar.gz
rust-c660cedc02e125fe47d90075837c5d8adeb4c097.zip
Add a GlobalAlloc trait
Diffstat (limited to 'src')
-rw-r--r--src/libcore/heap.rs30
1 files changed, 30 insertions, 0 deletions
diff --git a/src/libcore/heap.rs b/src/libcore/heap.rs
index 80eedb5bff2..5c51bb2b51b 100644
--- a/src/libcore/heap.rs
+++ b/src/libcore/heap.rs
@@ -404,6 +404,36 @@ impl From<AllocErr> for CollectionAllocErr {
     }
 }
 
+// FIXME: docs
+pub unsafe trait GlobalAlloc {
+    unsafe fn alloc(&self, layout: Layout) -> *mut Void;
+
+    unsafe fn dealloc(&self, ptr: *mut Void, layout: Layout);
+
+    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut Void {
+        let size = layout.size();
+        let ptr = self.alloc(layout);
+        if !ptr.is_null() {
+            ptr::write_bytes(ptr as *mut u8, 0, size);
+        }
+        ptr
+    }
+
+    unsafe fn realloc(&self, ptr: *mut Void, old_layout: Layout, new_size: usize) -> *mut Void {
+        let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align());
+        let new_ptr = self.alloc(new_layout);
+        if !new_ptr.is_null() {
+            ptr::copy_nonoverlapping(
+                ptr as *const u8,
+                new_ptr as *mut u8,
+                cmp::min(old_layout.size(), new_size),
+            );
+            self.dealloc(ptr, old_layout);
+        }
+        new_ptr
+    }
+}
+
 /// An implementation of `Alloc` can allocate, reallocate, and
 /// deallocate arbitrary blocks of data described via `Layout`.
 ///