Skip to content

Commit 059c706

Browse files
committed
Add safe alternative for initialization
The trade-off here is that the initialization might panic.
1 parent e578033 commit 059c706

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/lib.rs

+26
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,32 @@ impl Heap {
7373
self.holes = HoleList::new(heap_bottom, heap_size);
7474
}
7575

76+
/// Initialize an empty heap with provided memory.
77+
///
78+
/// The caller is responsible for procuring a region of raw memory that may be utilized by the
79+
/// allocator. This might be done via any method such as (unsafely) taking a region from the
80+
/// program's memory, from a mutable static, or by allocating and leaking such memory from
81+
/// another allocator.
82+
///
83+
/// The latter method may be especially useful if the underlying allocator does not perform
84+
/// deallocation (e.g. a simple bump allocator). Then the overlaid linked-list-allocator can
85+
/// provide memory reclamation.
86+
///
87+
/// # Panics
88+
///
89+
/// This method panics if the heap is already initialized.
90+
pub fn init_from_slice(&mut self, mem: &'static mut [MaybeUninit<u8>]) {
91+
assert!(self.bottom == 0, "The heap has already been initialized.");
92+
let size = mem.size();
93+
let address = mem.as_ptr() as usize;
94+
// Safety: All initialization requires the bottom address to be valid, which implies it
95+
// must not be 0. Initially the address is 0. The assertion above ensures that no
96+
// initialization had been called before.
97+
// The given address and size is valid according to the safety invariants of the mutable
98+
// reference handed to us by the caller.
99+
unsafe { self.init(address, size) }
100+
}
101+
76102
/// Creates a new heap with the given `bottom` and `size`. The bottom address must be valid
77103
/// and the memory in the `[heap_bottom, heap_bottom + heap_size)` range must not be used for
78104
/// anything else. This function is unsafe because it can cause undefined behavior if the

0 commit comments

Comments
 (0)