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

Modify Arc and Rc so the allocator is moved into the inner allocation #3540

Open
Enderlook opened this issue Dec 11, 2023 · 0 comments
Open

Comments

@Enderlook
Copy link

Enderlook commented Dec 11, 2023

Basically, at the moment Arc<T, A> uses:

pub struct Arc<T: ?Sized, A: Allocator = Global> {
    ptr: NonNull<ArcInner<T>>,
    phantom: PhantomData<ArcInner<T>>,
    alloc: A,
}

struct ArcInner<T: ?Sized> {
    strong: atomic::AtomicUsize,
    weak: atomic::AtomicUsize,
    data: T,
}

(Something similar happens in Rc, so this whole issue could also be applied to Rc.)

My idea is to move alloc from Arc to InnerArc:

pub struct Arc<T: ?Sized, A: Allocator = Global> {
    ptr: NonNull<ArcInner<T, A>>,
    phantom: PhantomData<ArcInner<T, A>>,
}

struct ArcInner<T: ?Sized, A> {
    strong: atomic::AtomicUsize,
    weak: atomic::AtomicUsize,
    alloc: A,
    data: T,
}

This would produce 2 benefits:

  1. The size of Arc is guaranteed to be the size of a single pointer, which is cool. Also, being more realistic, it means that if you have a non-zero-sized allocator, you don't have to pay the cost of its size on each clone of the instance, instead the allocator is stored in the inner pointer. That means that multiple copies of the same instance won't require multiple copies of the allocator, saving memory unlike the current approach,
  2. Doing this also means that A doesn't require implementing Clone if you want to clone the Arc, since it's stored in the shared pointer. This would relax the current Arc cloning implementation, no longer requiring A: Allocator + Clone but only A: Allocator. It would probably relax the same constrain in make_mut, unwrap_or_clone, downcast, downcast_unchecked, From<Vec<T, A>> for Arc<[T], A> and TryFrom<Arc<[T], A>> for Arc<[T; N], A>.
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

1 participant