lazy_heap/lib.rs
1//! # `lazy_heap`: A wrapper around the `slab_allocator_rs` crate that allows for lazy initialization
2//!
3//! Although there are plenty of global allocators in the crates.io repository, 3 years of tinkering with [my own kernel code](https://github.com/kennystrawnmusic/cryptos) have taught me that, sometimes, the more time saved, the better. As such, I came up with this in the code to my own kernel but decided, because of just how useful it really is, to actually open it up to the masses.
4//!
5//! ## Usage
6//! Using this crate allows you to use a closure to initialize the heap automatically (lazily) on the first access attempt:
7//!
8//! ```rust
9//! use lazy_heap::LazyHeap;
10//!
11//! #[global_allocator]
12//! pub static ALLOC: LazyHeap = LazyHeap::new(|| {
13//! // allocator initialization code goes here
14//! });
15//! ```
16//!
17//! This is a much more seamless, much less error-prone, set-it-and-forget-it way to initialize heap allocation than any other approach, because, with it, you can be guaranteed that any first attempt to use `alloc` will automatically initialize the heap for you.
18
19use core::alloc::{GlobalAlloc, Layout};
20use spin::Lazy;
21
22/// A re-export of `slab_allocator_rs::LockedHeap` for ease-of-use reasons.
23pub use slab_allocator_rs::LockedHeap;
24
25/// A wrapper around `slab_allocator_rs::LockedHeap` that initializes the heap lazily.
26pub struct LazyHeap(Lazy<LockedHeap>);
27
28impl LazyHeap {
29 /// Create a new `LazyHeap` with the given initialization function.
30 pub const fn new(init: fn() -> LockedHeap) -> Self {
31 Self(Lazy::new(init))
32 }
33
34 /// Create a new `LazyHeap` with the default initialization function.
35 pub const fn empty() -> Self {
36 Self(Lazy::new(|| LockedHeap::empty()))
37 }
38
39 /// Initialize the heap with the given range.
40 pub fn init(&self, begin: usize, len: usize) {
41 unsafe {
42 self.0.init(begin, len);
43 }
44 }
45}
46
47unsafe impl GlobalAlloc for LazyHeap {
48 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
49 unsafe { self.0.alloc(layout) }
50 }
51
52 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
53 unsafe { self.0.dealloc(ptr, layout) }
54 }
55}