why does allocate() use `[u8]` while deallocate uses `u8` in Allocator API?

    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);

from https://doc.rust-lang.org/std/alloc/trait.Allocator.html

I also note that in contrast, GlobalAlloc uses *mut u8 consistently https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html

    unsafe fn alloc(&self, layout: Layout) -> *mut u8;
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);

>Solution :

Note that this it is not decided yet what will be the final shape of this code, and it may change.

deallocate() takes NonNull<u8> because to deallocate memory you don’t need more than that. Only that pointer to the start of the allocation.

But for allocate(), allocators may over-allocate for various reasons. When they do that, it will be nice to inform the user that they over-allocated and how much. For example, a Vec may use this information to grow more than it initially wanted to, if the memory is available anyway.

This is why allocate() returns NonNull<[u8]>, to inform the caller what is the actual size of the allocation.

Leave a Reply