Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What about AllocRef and SyncAllocRef? #71

Closed
lachlansneff opened this issue Sep 5, 2020 · 3 comments
Closed

What about AllocRef and SyncAllocRef? #71

lachlansneff opened this issue Sep 5, 2020 · 3 comments

Comments

@lachlansneff
Copy link

lachlansneff commented Sep 5, 2020

I feel like this would provide the most ergonomic solution for working with both single-threaded and multi-threaded collections.

For a stack allocator, you'd pass &mut A into the collection. For a collection like a shared hashmap, you'd use an allocator that supported concurrent allocations and pass in &A. AllocRef would be implemented for either &A and &mut A depending on if it was concurrent or not.

It's definitely possible I'm not seeing some downsides of this, but it seems like the best of both worlds to me.

See my reply lower down.

@TimDiekmann

This comment has been minimized.

@lachlansneff
Copy link
Author

lachlansneff commented Sep 5, 2020

@TimDiekmann Yeah, I see. That is unfortunate. My other idea is that there could be two allocator traits, AllocRef and SyncAllocRef.

It'd look something like this:

pub unsafe trait SyncAllocRef: Sync + Send {
    fn alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr>;
    unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout);
    // ...
}

unsafe impl<A> AllocRef for A where A: SyncAllocRef {
    fn alloc(&mut self, layout: Layout) -> Result<NonNull<[u8]>, AllocErr> {
        <Self as SyncAllocRef>::alloc(self, layout)
    }
    unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
        <Self as SyncAllocRef>::dealloc(self, ptr, layout)
    }
}

Then, regular collections could just take an AllocRef and any allocator would work for them, and concurrent collections could explicitly take a SyncAllocRef.

It's explicit, idiomatic in all circumstances, and doesn't result in performance pitfalls.

@lachlansneff lachlansneff changed the title Has alloc taking self been ruled out? What about AllocRef and SyncAllocRef? Sep 5, 2020
@TimDiekmann
Copy link
Member

The idea isn't new, but I totally forgot about this approach, thank you for bringing this back! However I think this should be discussed in #55. I close this in favor of the other issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants