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

ACP: Generic Atomic<T> #443

Closed
CAD97 opened this issue Sep 16, 2024 · 2 comments
Closed

ACP: Generic Atomic<T> #443

CAD97 opened this issue Sep 16, 2024 · 2 comments
Labels
ACP-accepted API Change Proposal is accepted (seconded with no objections) api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api

Comments

@CAD97
Copy link

CAD97 commented Sep 16, 2024

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 to AtomicT.
  • Change the impl macros to use Atomic<T> instead of AtomicT.
  • Flip the alias direction so AtomicT is an alias of generic struct Atomic<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

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.
@CAD97 CAD97 added api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api labels Sep 16, 2024
@m-ou-se
Copy link
Member

m-ou-se commented Sep 17, 2024

We discussed this in the libs-api meeting just now. Please go ahead with these changes, as long as none of the changes affect the stable public interface.

@m-ou-se
Copy link
Member

m-ou-se commented Sep 17, 2024

128-bit atomics are interesting, since they are still unstable, but trait implementations cannot be unstable.

We can probably just stabilize 128 bit atomics before we stablize Atomic<T>.

@m-ou-se m-ou-se closed this as completed Sep 17, 2024
@m-ou-se m-ou-se added the ACP-accepted API Change Proposal is accepted (seconded with no objections) label Sep 17, 2024
workingjubilee added a commit to workingjubilee/rustc that referenced this issue Sep 19, 2024
Create `Atomic<T>` type alias

and use it in core/alloc/std where possible, ignoring test files for now.

This is step one, creating the alias from `Atomic<T>` to `AtomicT`. The next step of flipping this and aliasing `AtomicT` to `Atomic<T>` will have a bigger impact, since `AtomicT` imports can be dropped once `Atomic::new` is a usable name.

First commit is the true change. Second commit is mostly mechanical replacement of `AtomicT` type names with `Atomic<T>`.

See [how this was done for `NonZero`](rust-lang#120257) for the rough blueprint I'm following.

- ACP: rust-lang/libs-team#443 (comment)
- Tracking issue: rust-lang#130539
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ACP-accepted API Change Proposal is accepted (seconded with no objections) api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api
Projects
None yet
Development

No branches or pull requests

2 participants