88
99#![ no_std]
1010
11+ use core:: cell:: RefCell ;
1112use core:: alloc:: { GlobalAlloc , Layout } ;
1213use core:: ptr:: NonNull ;
1314
1415use cortex_m:: interrupt:: Mutex ;
1516use linked_list_allocator:: Heap ;
1617
1718pub struct CortexMHeap {
18- heap : Mutex < Heap > ,
19+ heap : Mutex < RefCell < Heap > > ,
1920}
2021
2122impl CortexMHeap {
@@ -25,7 +26,7 @@ impl CortexMHeap {
2526 /// [`init`](struct.CortexMHeap.html#method.init) method before using the allocator.
2627 pub const fn empty ( ) -> CortexMHeap {
2728 CortexMHeap {
28- heap : Mutex :: new ( Heap :: empty ( ) ) ,
29+ heap : Mutex :: new ( RefCell :: new ( Heap :: empty ( ) ) ) ,
2930 }
3031 }
3132
@@ -53,20 +54,29 @@ impl CortexMHeap {
5354 /// - This function must be called exactly ONCE.
5455 /// - `size > 0`
5556 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+ } ) ;
5763 }
5864}
5965
6066unsafe impl GlobalAlloc for CortexMHeap {
6167 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)
6472 . ok ( )
65- . map_or ( 0 as * mut u8 , |allocation| allocation. as_ptr ( ) )
73+ . map_or ( 0 as * mut u8 , |allocation| allocation. as_ptr ( ) ) )
6674 }
6775
6876 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) ) ;
7181 }
7282}
0 commit comments