11use core:: alloc:: { GlobalAlloc , Layout } ;
2- use core:: cell:: RefCell ;
2+ use core:: cell:: { OnceCell , RefCell } ;
33use core:: ptr:: { self , NonNull } ;
44
55use critical_section:: Mutex ;
66use linked_list_allocator:: Heap as LLHeap ;
77
88/// A linked list first fit heap.
99pub struct Heap {
10- heap : Mutex < RefCell < LLHeap > > ,
10+ heap : Mutex < RefCell < OnceCell < LLHeap > > > ,
1111}
1212
1313impl Heap {
@@ -17,7 +17,7 @@ impl Heap {
1717 /// [`init`](Self::init) method before using the allocator.
1818 pub const fn empty ( ) -> Heap {
1919 Heap {
20- heap : Mutex :: new ( RefCell :: new ( LLHeap :: empty ( ) ) ) ,
20+ heap : Mutex :: new ( RefCell :: new ( OnceCell :: new ( ) ) ) ,
2121 }
2222 }
2323
@@ -39,36 +39,36 @@ impl Heap {
3939 /// `0x1000` and `size` is `0x30000` then the allocator won't use memory at
4040 /// addresses `0x31000` and larger.
4141 ///
42- /// # Safety
42+ /// # Panics
4343 ///
44- /// Obey these or Bad Stuff will happen.
45- ///
46- /// - This function must be called exactly ONCE.
47- /// - `size > 0`
44+ /// Calling this function multiple times or with `size == 0` will cause a panic.
4845 pub unsafe fn init ( & self , start_addr : usize , size : usize ) {
46+ assert ! ( size > 0 ) ;
4947 critical_section:: with ( |cs| {
50- self . heap
51- . borrow ( cs)
52- . borrow_mut ( )
53- . init ( start_addr as * mut u8 , size) ;
48+ assert ! ( self
49+ . heap
50+ . borrow_ref_mut( cs)
51+ . set( LLHeap :: new( start_addr as * mut u8 , size) )
52+ . is_ok( ) ) ;
5453 } ) ;
5554 }
5655
5756 /// Returns an estimate of the amount of bytes in use.
5857 pub fn used ( & self ) -> usize {
59- critical_section:: with ( |cs| self . heap . borrow ( cs) . borrow_mut ( ) . used ( ) )
58+ critical_section:: with ( |cs| self . heap . borrow_ref_mut ( cs) . get_mut ( ) . unwrap ( ) . used ( ) )
6059 }
6160
6261 /// Returns an estimate of the amount of bytes available.
6362 pub fn free ( & self ) -> usize {
64- critical_section:: with ( |cs| self . heap . borrow ( cs) . borrow_mut ( ) . free ( ) )
63+ critical_section:: with ( |cs| self . heap . borrow_ref_mut ( cs) . get_mut ( ) . unwrap ( ) . free ( ) )
6564 }
6665
6766 fn alloc ( & self , layout : Layout ) -> Option < NonNull < u8 > > {
6867 critical_section:: with ( |cs| {
6968 self . heap
70- . borrow ( cs)
71- . borrow_mut ( )
69+ . borrow_ref_mut ( cs)
70+ . get_mut ( )
71+ . unwrap ( )
7272 . allocate_first_fit ( layout)
7373 . ok ( )
7474 } )
@@ -77,8 +77,9 @@ impl Heap {
7777 unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
7878 critical_section:: with ( |cs| {
7979 self . heap
80- . borrow ( cs)
81- . borrow_mut ( )
80+ . borrow_ref_mut ( cs)
81+ . get_mut ( )
82+ . unwrap ( )
8283 . deallocate ( NonNull :: new_unchecked ( ptr) , layout)
8384 } ) ;
8485 }
0 commit comments