33//! # Example
44//!
55//! ```
6- //! #![feature(alloc)]
76//! #![feature(global_allocator)]
87//! #![feature(lang_items)]
98//!
@@ -53,14 +52,15 @@ extern crate alloc;
5352extern crate cortex_m;
5453extern crate linked_list_allocator;
5554
55+ use core:: cell:: RefCell ;
5656use core:: alloc:: { GlobalAlloc , Layout } ;
5757use core:: ptr:: NonNull ;
5858
5959use cortex_m:: interrupt:: Mutex ;
6060use linked_list_allocator:: Heap ;
6161
6262pub struct CortexMHeap {
63- heap : Mutex < Heap > ,
63+ heap : Mutex < RefCell < Heap > > ,
6464}
6565
6666impl CortexMHeap {
@@ -70,7 +70,7 @@ impl CortexMHeap {
7070 /// [`init`](struct.CortexMHeap.html#method.init) method before using the allocator.
7171 pub const fn empty ( ) -> CortexMHeap {
7272 CortexMHeap {
73- heap : Mutex :: new ( Heap :: empty ( ) ) ,
73+ heap : Mutex :: new ( RefCell :: new ( Heap :: empty ( ) ) ) ,
7474 }
7575 }
7676
@@ -98,20 +98,29 @@ impl CortexMHeap {
9898 /// - This function must be called exactly ONCE.
9999 /// - `size > 0`
100100 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+ } ) ;
102107 }
103108}
104109
105110unsafe impl GlobalAlloc for CortexMHeap {
106111 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 ( ) ) )
111118 }
112119
113120 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) ) ;
116125 }
117126}
0 commit comments