File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ use super :: { Locked , align_up} ;
2+ use alloc:: alloc:: { GlobalAlloc , Layout } ;
3+ use core:: ptr;
4+
5+ /// A simple bump allocator.
6+ pub struct BumpAllocator {
7+ heap_start : usize ,
8+ heap_end : usize ,
9+ next : usize ,
10+ allocations : usize ,
11+ }
12+
13+ impl BumpAllocator {
14+ /// Create a new empty bump allocator.
15+ pub const fn new ( ) -> Self {
16+ BumpAllocator {
17+ heap_start : 0 ,
18+ heap_end : 0 ,
19+ next : 0 ,
20+ allocations : 0 ,
21+ }
22+ }
23+
24+ /// Initializes a bump alloactor for a given heap start and heap size
25+ ///
26+ /// This function is unsafe as it is up to the caller to ensure that the values
27+ /// for heap start and heap size are valid.
28+ pub unsafe fn init ( & mut self , heap_start : usize , heap_size : usize ) {
29+ self . heap_start = heap_start;
30+ self . heap_end = heap_start + heap_size;
31+ self . next = heap_start;
32+ }
33+ }
34+
35+ unsafe impl GlobalAlloc for Locked < BumpAllocator > {
36+ unsafe fn alloc ( & self , layout : Layout ) -> * mut u8 {
37+ let mut bump = self . lock ( ) ;
38+
39+ let alloc_start = align_up ( bump. next , layout. align ( ) ) ;
40+ let alloc_end = match alloc_start. checked_add ( layout. size ( ) )
41+ {
42+ Some ( end) => end,
43+ None => return ptr:: null_mut ( ) ,
44+ } ;
45+
46+ if alloc_end > bump. heap_end {
47+ ptr:: null_mut ( )
48+ } else {
49+ bump. next = alloc_end;
50+ bump. allocations += 1 ;
51+ alloc_start as * mut u8
52+ }
53+ }
54+
55+ unsafe fn dealloc ( & self , ptr : * mut u8 , layout : Layout ) {
56+ todo ! ( )
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments