Description
Proposal
Problem statement
The std::sync::atomic
module contains 12 different Atomic*
types with nearly identical API. However, there's no good way to associate a primitive type with its counterpart atomic cell, nor to use atomics with the various FFI integer type aliases.
Like was done for NonZero*
in 1.79, this can be cleanly addressed with a generic type Atomic<T: AtomicPrimitive>
.
This ACP does not propose to support Atomic<T>
for any types that do not already have an Atomic*
type defined.
Solution sketch
Implementation would proceed in a few steps:
- Implement
Atomic<T>
as a type alias toAtomicT
. - Change the impl macros to use
Atomic<T>
instead ofAtomicT
. - Flip the alias direction so
AtomicT
is an alias of generic structAtomic<T>
. - Unify methods on the generic type as desired.
This ACP only proposes unifying the nonatomic methods initially. The other methods can and should be eventually unified, but this limits the initial scope and avoids trying to unify disparate stability annotations, or addressing AtomicPtr
and AtomicBool
's slightly different API.
128-bit atomics are interesting, since they are still unstable, but trait implementations cannot be unstable. To avoid premature stabilization of Atomic<i128>
, either AtomicI128
can be left as a separately implemented type, or Atomic
can mention an unstable middleman marker type instead of i128
directly as the generic.
The result API would be about: (cfgs omitted)
// core::sync::atomic
pub type AtomicBool = Atomic<bool>;
pub type AtomicU8 = Atomic<u8>;
pub type AtomicI8 = Atomic<i8>;
// … snip …
pub type AtomicPtr<T> = Atomic<*mut T>;
#[repr(C)]
pub struct Atomic<T: AtomicPrimitive>(T::AtomicInner);
#[sealed]
#[unstable]
pub unsafe trait AtomicPrimitive: Sized + Copy {
#[doc(hidden)]
type AtomicInner;
}
macro atom($Inner:ident($Primitive:ty), $align:literal) {
unsafe impl AtomicPrimitive for $Primitive {
type AtomicInner = $Inner;
}
#[repr(C, align($align))]
pub(self) struct $Inner(UnsafeCell<$Primitive>);
}
atom!(AtomicBoolInner(bool), 1);
atom!(AtomicU8Inner(u8), 1);
atom!(AtomicI8Inner(i8), 1);
// … snip …
#[cfg(target_pointer_width = "32")]
atom!(AtomicPtrInner<T>(*mut T), 4);
#[cfg(target_pointer_width = "64")]
atom!(AtomicPtrInner<T>(*mut T), 8);
// hide AtomicInner impl detail from docs
impl<T> !Freeze for Atomic<T> {}
unsafe impl<T> Send for Atomic<T> {}
unsafe impl<T> Sync for Atomic<T> {}
impl<T> Unpin for Atomic<T> {}
impl<T> UnwindSafe for Atomic<T> {}
impl<T> RefUnwindSafe for Atomic<T> {}
// generic methods
impl<T> From<T> for Atomic<T>;
impl<T> Atomic<T> {
pub const fn new(v: T) -> Self;
pub const fn as_ptr(&self) -> *mut T;
pub const unsafe fn from_ptr(p: *mut T) -> &Self;
pub const fn into_inner(self) -> T;
}
// all other functionality remains implemented individually on Atomic*, not generically for now
I am volunteering to do this implementation work, if this is determined a desirable refactor.
Alternatives
This API plan only encodes the equivalent of cfg(target_has_atomic_load_store = "N")
into the type system (as iN: AtomicPrimitive
). The other two atomic cfgs could also be encoded. Notably, target_has_atomic_equal_alignment
has a reasonably meaningful potential spelling of T: AtomicPrimitive<AlignedForAtomic = T>
.
This can be done in a 3rd party crate instead of std, and crates already exist to provide this or a more general AtomicCell
. However, the target ideal end state (functions on Atomic<T>
and not Atomic*
) provides a cleaner API surface for Rust than the current apparent duplication.
Additionally, using a generic enables future work that extends Atomic<*mut T>
to also support *const T
, &T
, and NonNull<T>
, if so desired, as well as atomic double (fat) pointers.
Links and related work
NonZero*
's migration to use a generic: Tracking Issue for genericNonZero
rust#120257- The
radium
crate'sAtom<T>
works like this ACP'sAtomic<T>
. (The crate primarily exists to provide a unified API for atomics andCell
.) - Minimal proof of concept: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=0cc4433226faef926113027d5f0b681f
- Swift atomics: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0410-atomics.md
- Internals discourse: https://internals.rust-lang.org/t/generic-atomic-t/21547?u=cad97
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.