File tree Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -23,6 +23,9 @@ license = "MIT OR Apache-2.0"
23
23
name = " embedded-alloc"
24
24
version = " 0.5.0"
25
25
26
+ [features ]
27
+ allocator_api = []
28
+
26
29
[dependencies ]
27
30
critical-section = " 1.0"
28
31
Original file line number Diff line number Diff line change
1
+ nightly
Original file line number Diff line number Diff line change 1
1
#![ doc = include_str ! ( "../README.md" ) ]
2
2
#![ no_std]
3
+ #![ cfg_attr(
4
+ feature = "allocator_api" ,
5
+ feature( allocator_api, nonnull_slice_from_raw_parts, alloc_layout_extra)
6
+ ) ]
3
7
4
8
use core:: alloc:: { GlobalAlloc , Layout } ;
5
9
use core:: cell:: RefCell ;
@@ -88,3 +92,40 @@ unsafe impl GlobalAlloc for Heap {
88
92
} ) ;
89
93
}
90
94
}
95
+
96
+ #[ cfg( feature = "allocator_api" ) ]
97
+ mod allocator_api {
98
+ use core:: {
99
+ alloc:: { AllocError , Allocator , Layout } ,
100
+ ptr:: NonNull ,
101
+ } ;
102
+
103
+ use crate :: Heap ;
104
+
105
+ unsafe impl Allocator for Heap {
106
+ fn allocate ( & self , layout : Layout ) -> Result < NonNull < [ u8 ] > , AllocError > {
107
+ match layout. size ( ) {
108
+ 0 => Ok ( NonNull :: slice_from_raw_parts ( layout. dangling ( ) , 0 ) ) ,
109
+ size => critical_section:: with ( |cs| {
110
+ self . heap
111
+ . borrow ( cs)
112
+ . borrow_mut ( )
113
+ . allocate_first_fit ( layout)
114
+ . map ( |allocation| NonNull :: slice_from_raw_parts ( allocation, size) )
115
+ . map_err ( |_| AllocError )
116
+ } ) ,
117
+ }
118
+ }
119
+
120
+ unsafe fn deallocate ( & self , ptr : NonNull < u8 > , layout : Layout ) {
121
+ if layout. size ( ) != 0 {
122
+ critical_section:: with ( |cs| {
123
+ self . heap
124
+ . borrow ( cs)
125
+ . borrow_mut ( )
126
+ . deallocate ( NonNull :: new_unchecked ( ptr. as_ptr ( ) ) , layout)
127
+ } ) ;
128
+ }
129
+ }
130
+ }
131
+ }
You can’t perform that action at this time.
0 commit comments