Skip to content

Use a struct to represent a memory block #51

Closed
rust-lang/rust
#70362
@TimDiekmann

Description

@TimDiekmann

EDIT: Removed MemoryLayout<T> as #50 was closed.

While adding ReallocPlacement to get rid of grow_in_place and shrink_in_place I noticed, that neither of them returning a pointer, so the signatures can't be merged.
If we restructure the signatures of AllocRef a bit, we'll get a more convenient interface. First, I'll introduce a new struct:

struct MemoryBlock {
    ptr: Unique<u8>,
    layout: Layout,
}

Now, the signatures of AllocRef can be changed:

pub unsafe trait AllocRef {
    fn alloc(
        &mut self,
        layout: Layout,
        init: AllocInit,
    ) -> Result<MemoryBlock, AllocError>;

    unsafe fn dealloc(&mut self, memory: MemoryBlock);

    unsafe fn grow(
        &mut self,
        memory: &mut MemoryBlock,
        new_size: usize,
        placement: ReallocPlacement,
        init: AllocInit,
    ) -> Result<(), AllocError> { ... }

    unsafe fn shrink(
        &mut self,
        memory: &mut MemoryBlock,
        new_size: usize,
        placement: ReallocPlacement,
    ) -> Result<(), AllocError> { ... }
}

This API feels much more rusty. It returns a block when allocating, it's passed as mutable reference, when it is changed, and it's moved out of scope when deallocating.

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