Skip to content

Change the signatures of AllocRef to take self instead of &mut self #37

Closed
@TimDiekmann

Description

@TimDiekmann

The gamedev WG made a proof of concept with our new AllocRef and BuildAllocRef trait (implemented at the alloc-wg crate) by implementing them for bumpalo.

It turned out, as mentioned in TimDiekmann/alloc-wg#11, that taking &mut self isn't always the best way to implement AllocRef. I would like to recall once again that AllocRef should not be implemented on stateful structs. That was the reason why we renamed Alloc to AllocRef in #8.

@Wodann and I discussed a bit about this problem in the gamedev discord channel and my suggestion is to take self instead of &mut self. This solves several issues:

  • AllocRef can be implemented on ZST types as before (e.g. Global and System)
  • For non-ZST and non-Copy types, the user can chose between implementing it on &MyAllocator and &mut MyAllocator This does not work at all -> Closed
  • A oneshot allocator is trivially implementable
  • Probably solves Implementing AllocRef for actual references #34

The resulting API would look like this:

pub trait BuildAllocRef: Sized {
    type Ref: DeallocRef<BuildAlloc = Self>;

    unsafe fn build_alloc_ref(
        &mut self, // Stick with `&mut self` or change this to `self` as well?
        ptr: NonNull<u8>,
        layout: Option<NonZeroLayout>,
    ) -> Self::Ref;
}

pub trait DeallocRef: Sized + Copy {
    type BuildAlloc: BuildAllocRef<Ref = Self>;

    fn get_build_alloc(self) -> Self::BuildAlloc;

    unsafe fn dealloc(self, ptr: NonNull<u8>, layout: NonZeroLayout);
}


pub trait AllocRef: DeallocRef {
    type Error;

    fn alloc(self, layout: NonZeroLayout) -> Result<NonNull<u8>, Self::Error>;

    // ...
}

pub trait ReallocRef: AllocRef {
    unsafe fn realloc(
        self,
        ptr: NonNull<u8>,
        old_layout: NonZeroLayout,
        new_layout: NonZeroLayout,
    ) -> Result<NonNull<u8>, Self::Error> {
        // ...
    } 
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions