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"
2323name = " embedded-alloc"
2424version = " 0.5.0"
2525
26+ [features ]
27+ allocator_api = []
28+
2629[dependencies ]
2730critical-section = " 1.0"
2831
Original file line number Diff line number Diff line change 1+ nightly
Original file line number Diff line number Diff line change 11#![ doc = include_str ! ( "../README.md" ) ]
22#![ no_std]
3+ #![ cfg_attr(
4+ feature = "allocator_api" ,
5+ feature( allocator_api, nonnull_slice_from_raw_parts, alloc_layout_extra)
6+ ) ]
37
48use core:: alloc:: { GlobalAlloc , Layout } ;
59use core:: cell:: RefCell ;
@@ -88,3 +92,40 @@ unsafe impl GlobalAlloc for Heap {
8892 } ) ;
8993 }
9094}
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