Skip to content

[Suggestion]: Implement alloc::alloc::Allocator Trait with Problem. #28

@lvyuemeng

Description

@lvyuemeng

Description

I want to use the experiment feature allocator_api by implement the trait Allocator for Arena.
Here my code:

use rarena_allocator::Allocator as RAllocator;

unsafe impl Allocator for ShmArena {
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, core::alloc::AllocError> {
        let size = layout.size();
        RAllocator::alloc_aligned_bytes_owned::<u8>(&self.0, size as u32)
            .map(|b| b.deref().into())
            .map_err(|_| core::alloc::AllocError)
    }

    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
        let size = layout.size();
        unsafe {
            let offset = RAllocator::offset(&self.0, ptr.as_ptr());
            RAllocator::dealloc(&self.0, offset as u32, size as u32);
        }
    }
}

But it turns out a wrong approach, I try to test it with:

        // shm_arena: Arena;
        let layout = Layout::new::<u8>();
        unsafe {
            let m: NonNull<u8> = shm_arena.allocate(layout).unwrap().cast();
            let data = m.as_ptr();
            let mut b = Box::from_raw_in(data, shm_arena.clone());
            *b = 2; // <- panic!
            assert_eq!(*b, 2);
        }
        // shm_arena: Arena;
        let layout = Layout::new::<u8>();
        unsafe {
            let m: NonNull<u8> = shm_arena.allocate(layout).unwrap().cast();
            m.write(1); // <- panic!
        }

Which yields (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION).

I don't know how to implement a correct version for alloc::Allocator, it would be better to be implemented natively.

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