Skip to content

Simple bump allocator #3

Description

@AngelicosPhosphoros

It would be nice to have a simple bump allocator without extra tracking of freed blocks.
This would make generated machine code for common case shorter.

I imagine it would be like this:

#[repr(C)]
struct BumpStalloc<const L: usize, const B: usize> {
   _align: Align<B>,
   buffer: UnsafeCell<[MaybeUninit<[u8; B]>; L]>,
   next_free_block: usize,
   count_living_allocs: usize,
}

fn alloc(&self, layout: Layout)->Result<NonNull<[u8]>, AllocError>{
    let blocks = /* calc blocks */
    if self.next_free_block + blocks <= L {
        let res_ptr = (buffer.get() as *mut u8).add(self.next_free_block * L)
        self.next_free_block += blocks;
        self.count_living_allocs += 1;
        Ok(slice from res_ptr)
    } else {
        Err()
    }
}

fn grow(&self, layout: Layout)->Result<NonNull<[u8]>, AllocError>{
    if is_last() {
       try_extend();
    } else {
       Err()
    }
}

fn dealloc(&self, ptr, layout) {
    if is_last() {
       next_free_block -= length;
    }
    count_living_allocs -= 1;
    if count_living_allocs == 0 {
       // No living allocations, can safely reset.
       // next_free_block may be not naturally 0 if allocs/deallocs didn't
       // happen in stricly symmetrical fashion
       next_free_block = 0;
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions