1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#![no_std]
#![cfg_attr(feature = "oom-handler", feature(alloc_error_handler))]
use core::{
alloc::{GlobalAlloc, Layout},
cell::RefCell,
ptr::{self, NonNull},
};
use bare_metal::Mutex;
use linked_list_allocator::Heap;
#[cfg(target_arch = "riscv32")]
use riscv::interrupt;
#[cfg(target_arch = "xtensa")]
use xtensa_lx::interrupt;
#[cfg(feature = "oom-handler")]
#[alloc_error_handler]
fn oom(_: core::alloc::Layout) -> ! {
panic!("Allocation failed, out of memory");
}
pub struct EspHeap {
heap: Mutex<RefCell<Heap>>,
}
impl EspHeap {
pub const fn empty() -> EspHeap {
EspHeap {
heap: Mutex::new(RefCell::new(Heap::empty())),
}
}
pub unsafe fn init(&self, heap_bottom: *mut u8, size: usize) {
interrupt::free(|cs| self.heap.borrow(*cs).borrow_mut().init(heap_bottom, size));
}
pub fn used(&self) -> usize {
interrupt::free(|cs| self.heap.borrow(*cs).borrow_mut().used())
}
pub fn free(&self) -> usize {
interrupt::free(|cs| self.heap.borrow(*cs).borrow_mut().free())
}
}
unsafe impl GlobalAlloc for EspHeap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
interrupt::free(|cs| {
self.heap
.borrow(*cs)
.borrow_mut()
.allocate_first_fit(layout)
.ok()
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
})
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
interrupt::free(|cs| {
self.heap
.borrow(*cs)
.borrow_mut()
.deallocate(NonNull::new_unchecked(ptr), layout)
});
}
}