3
3
//! # Example
4
4
//!
5
5
//! ```
6
- //! #![feature(alloc)]
7
6
//! #![feature(global_allocator)]
8
7
//! #![feature(lang_items)]
9
8
//!
@@ -53,14 +52,15 @@ extern crate alloc;
53
52
extern crate cortex_m;
54
53
extern crate linked_list_allocator;
55
54
55
+ use core:: cell:: RefCell ;
56
56
use core:: alloc:: { GlobalAlloc , Layout } ;
57
57
use core:: ptr:: NonNull ;
58
58
59
59
use cortex_m:: interrupt:: Mutex ;
60
60
use linked_list_allocator:: Heap ;
61
61
62
62
pub struct CortexMHeap {
63
- heap : Mutex < Heap > ,
63
+ heap : Mutex < RefCell < Heap > > ,
64
64
}
65
65
66
66
impl CortexMHeap {
@@ -70,7 +70,7 @@ impl CortexMHeap {
70
70
/// [`init`](struct.CortexMHeap.html#method.init) method before using the allocator.
71
71
pub const fn empty ( ) -> CortexMHeap {
72
72
CortexMHeap {
73
- heap : Mutex :: new ( Heap :: empty ( ) ) ,
73
+ heap : Mutex :: new ( RefCell :: new ( Heap :: empty ( ) ) ) ,
74
74
}
75
75
}
76
76
@@ -98,20 +98,29 @@ impl CortexMHeap {
98
98
/// - This function must be called exactly ONCE.
99
99
/// - `size > 0`
100
100
pub unsafe fn init ( & self , start_addr : usize , size : usize ) {
101
- self . heap . lock ( |heap| heap. init ( start_addr, size) ) ;
101
+ cortex_m:: interrupt:: free ( |cs| {
102
+ self . heap
103
+ . borrow ( cs)
104
+ . borrow_mut ( )
105
+ . init ( start_addr, size) ;
106
+ } ) ;
102
107
}
103
108
}
104
109
105
110
unsafe impl GlobalAlloc for CortexMHeap {
106
111
unsafe fn alloc ( & self , layout : Layout ) -> * mut u8 {
107
- self . heap
108
- . lock ( |heap| heap. allocate_first_fit ( layout) )
109
- . ok ( )
110
- . map_or ( 0 as * mut u8 , |allocation| allocation. as_ptr ( ) )
112
+ cortex_m:: interrupt:: free ( |cs| self . heap
113
+ . borrow ( cs)
114
+ . borrow_mut ( )
115
+ . allocate_first_fit ( layout)
116
+ . ok ( )
117
+ . map_or ( 0 as * mut u8 , |allocation| allocation. as_ptr ( ) ) )
111
118
}
112
119
113
120
unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
114
- self . heap
115
- . lock ( |heap| heap. deallocate ( NonNull :: new_unchecked ( ptr) , layout) ) ;
121
+ cortex_m:: interrupt:: free ( |cs| self . heap
122
+ . borrow ( cs)
123
+ . borrow_mut ( )
124
+ . deallocate ( NonNull :: new_unchecked ( ptr) , layout) ) ;
116
125
}
117
126
}
0 commit comments