8
8
9
9
#![ no_std]
10
10
11
+ use core:: cell:: RefCell ;
11
12
use core:: alloc:: { GlobalAlloc , Layout } ;
12
13
use core:: ptr:: NonNull ;
13
14
14
15
use cortex_m:: interrupt:: Mutex ;
15
16
use linked_list_allocator:: Heap ;
16
17
17
18
pub struct CortexMHeap {
18
- heap : Mutex < Heap > ,
19
+ heap : Mutex < RefCell < Heap > > ,
19
20
}
20
21
21
22
impl CortexMHeap {
@@ -25,7 +26,7 @@ impl CortexMHeap {
25
26
/// [`init`](struct.CortexMHeap.html#method.init) method before using the allocator.
26
27
pub const fn empty ( ) -> CortexMHeap {
27
28
CortexMHeap {
28
- heap : Mutex :: new ( Heap :: empty ( ) ) ,
29
+ heap : Mutex :: new ( RefCell :: new ( Heap :: empty ( ) ) ) ,
29
30
}
30
31
}
31
32
@@ -53,20 +54,29 @@ impl CortexMHeap {
53
54
/// - This function must be called exactly ONCE.
54
55
/// - `size > 0`
55
56
pub unsafe fn init ( & self , start_addr : usize , size : usize ) {
56
- self . heap . lock ( |heap| heap. init ( start_addr, size) ) ;
57
+ cortex_m:: interrupt:: free ( |cs| {
58
+ self . heap
59
+ . borrow ( cs)
60
+ . borrow_mut ( )
61
+ . init ( start_addr, size) ;
62
+ } ) ;
57
63
}
58
64
}
59
65
60
66
unsafe impl GlobalAlloc for CortexMHeap {
61
67
unsafe fn alloc ( & self , layout : Layout ) -> * mut u8 {
62
- self . heap
63
- . lock ( |heap| heap. allocate_first_fit ( layout) )
68
+ cortex_m:: interrupt:: free ( |cs| self . heap
69
+ . borrow ( cs)
70
+ . borrow_mut ( )
71
+ . allocate_first_fit ( layout)
64
72
. ok ( )
65
- . map_or ( 0 as * mut u8 , |allocation| allocation. as_ptr ( ) )
73
+ . map_or ( 0 as * mut u8 , |allocation| allocation. as_ptr ( ) ) )
66
74
}
67
75
68
76
unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
69
- self . heap
70
- . lock ( |heap| heap. deallocate ( NonNull :: new_unchecked ( ptr) , layout) ) ;
77
+ cortex_m:: interrupt:: free ( |cs| self . heap
78
+ . borrow ( cs)
79
+ . borrow_mut ( )
80
+ . deallocate ( NonNull :: new_unchecked ( ptr) , layout) ) ;
71
81
}
72
82
}
0 commit comments