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
19#![no_std]
20
21use core::alloc::{GlobalAlloc, Layout};
22use spin::Lazy;
23
24/// A re-export of `slab_allocator_rs::LockedHeap` for ease-of-use reasons.
25pub use slab_allocator_rs::LockedHeap;
26
27/// A wrapper around `slab_allocator_rs::LockedHeap` that initializes the heap lazily.
28pub struct LazyHeap(Lazy<LockedHeap>);
29
30impl LazyHeap {
31    /// Create a new `LazyHeap` with the given initialization function.
32    pub const fn new(init: fn() -> LockedHeap) -> Self {
33        Self(Lazy::new(init))
34    }
35
36    /// Create a new `LazyHeap` with the default initialization function.
37    pub const fn empty() -> Self {
38        Self(Lazy::new(|| LockedHeap::empty()))
39    }
40
41    /// Initialize the heap with the given range.
42    pub fn init(&self, begin: usize, len: usize) {
43        unsafe {
44            self.0.init(begin, len);
45        }
46    }
47}
48
49unsafe impl GlobalAlloc for LazyHeap {
50    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
51        unsafe { self.0.alloc(layout) }
52    }
53
54    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
55        unsafe { self.0.dealloc(ptr, layout) }
56    }
57}