1
1
use core:: alloc:: { GlobalAlloc , Layout } ;
2
- use core:: cell:: RefCell ;
2
+ use core:: cell:: { OnceCell , RefCell } ;
3
3
use core:: ptr:: { self , NonNull } ;
4
4
5
5
use critical_section:: Mutex ;
6
6
use linked_list_allocator:: Heap as LLHeap ;
7
7
8
8
/// A linked list first fit heap.
9
9
pub struct Heap {
10
- heap : Mutex < RefCell < LLHeap > > ,
10
+ heap : Mutex < RefCell < OnceCell < LLHeap > > > ,
11
11
}
12
12
13
13
impl Heap {
@@ -17,7 +17,7 @@ impl Heap {
17
17
/// [`init`](Self::init) method before using the allocator.
18
18
pub const fn empty ( ) -> Heap {
19
19
Heap {
20
- heap : Mutex :: new ( RefCell :: new ( LLHeap :: empty ( ) ) ) ,
20
+ heap : Mutex :: new ( RefCell :: new ( OnceCell :: new ( ) ) ) ,
21
21
}
22
22
}
23
23
@@ -46,29 +46,32 @@ impl Heap {
46
46
/// - This function must be called exactly ONCE.
47
47
/// - `size > 0`
48
48
pub unsafe fn init ( & self , start_addr : usize , size : usize ) {
49
+ assert ! ( size > 0 ) ;
49
50
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( ) ) ;
54
56
} ) ;
55
57
}
56
58
57
59
/// Returns an estimate of the amount of bytes in use.
58
60
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 ( ) )
60
62
}
61
63
62
64
/// Returns an estimate of the amount of bytes available.
63
65
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 ( ) )
65
67
}
66
68
67
69
fn alloc ( & self , layout : Layout ) -> Option < NonNull < u8 > > {
68
70
critical_section:: with ( |cs| {
69
71
self . heap
70
- . borrow ( cs)
71
- . borrow_mut ( )
72
+ . borrow_ref_mut ( cs)
73
+ . get_mut ( )
74
+ . unwrap ( )
72
75
. allocate_first_fit ( layout)
73
76
. ok ( )
74
77
} )
@@ -77,8 +80,9 @@ impl Heap {
77
80
unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
78
81
critical_section:: with ( |cs| {
79
82
self . heap
80
- . borrow ( cs)
81
- . borrow_mut ( )
83
+ . borrow_ref_mut ( cs)
84
+ . get_mut ( )
85
+ . unwrap ( )
82
86
. deallocate ( NonNull :: new_unchecked ( ptr) , layout)
83
87
} ) ;
84
88
}
0 commit comments