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
@@ -46,29 +46,32 @@ impl Heap {
4646 /// - This function must be called exactly ONCE.
4747 /// - `size > 0`
4848 pub unsafe fn init ( & self , start_addr : usize , size : usize ) {
49+ assert ! ( size > 0 ) ;
4950 critical_section:: with ( |cs| {
50- self . heap
51- . borrow ( cs)
52- . borrow_mut ( )
53- . init ( start_addr as * mut u8 , size) ;
51+ assert ! ( self
52+ . heap
53+ . borrow_ref_mut( cs)
54+ . set( LLHeap :: new( start_addr as * mut u8 , size) )
55+ . is_ok( ) ) ;
5456 } ) ;
5557 }
5658
5759 /// Returns an estimate of the amount of bytes in use.
5860 pub fn used ( & self ) -> usize {
59- critical_section:: with ( |cs| self . heap . borrow ( cs) . borrow_mut ( ) . used ( ) )
61+ critical_section:: with ( |cs| self . heap . borrow_ref_mut ( cs) . get_mut ( ) . unwrap ( ) . used ( ) )
6062 }
6163
6264 /// Returns an estimate of the amount of bytes available.
6365 pub fn free ( & self ) -> usize {
64- critical_section:: with ( |cs| self . heap . borrow ( cs) . borrow_mut ( ) . free ( ) )
66+ critical_section:: with ( |cs| self . heap . borrow_ref_mut ( cs) . get_mut ( ) . unwrap ( ) . free ( ) )
6567 }
6668
6769 fn alloc ( & self , layout : Layout ) -> Option < NonNull < u8 > > {
6870 critical_section:: with ( |cs| {
6971 self . heap
70- . borrow ( cs)
71- . borrow_mut ( )
72+ . borrow_ref_mut ( cs)
73+ . get_mut ( )
74+ . unwrap ( )
7275 . allocate_first_fit ( layout)
7376 . ok ( )
7477 } )
@@ -77,8 +80,9 @@ impl Heap {
7780 unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
7881 critical_section:: with ( |cs| {
7982 self . heap
80- . borrow ( cs)
81- . borrow_mut ( )
83+ . borrow_ref_mut ( cs)
84+ . get_mut ( )
85+ . unwrap ( )
8286 . deallocate ( NonNull :: new_unchecked ( ptr) , layout)
8387 } ) ;
8488 }
0 commit comments