Skip to main content

atomic_primitive/
lib.rs

1#![doc = include_str!("../README.md")]
2#![no_std]
3
4#[macro_use]
5mod macros;
6
7mod atomic;
8mod integer;
9mod signed;
10mod unsigned;
11
12#[cfg(test)]
13mod tests;
14
15pub use self::atomic::PrimitiveAtomic;
16pub use self::integer::PrimitiveAtomicInteger;
17pub use self::signed::PrimitiveAtomicSigned;
18pub use self::unsigned::PrimitiveAtomicUnsigned;
19
20trait Sealed {}
21
22/// Maps a non-atomic primitive type to its corresponding atomic type.
23///
24/// This mirrors the unstable [`core::sync::atomic::AtomicPrimitive`] trait.
25/// Once that trait is stabilized, this can be deprecated in favor of the std
26/// version.
27///
28/// # Examples
29///
30/// ```
31/// use atomic_primitive::{AtomicPrimitive, PrimitiveAtomic};
32/// use core::sync::atomic::Ordering;
33///
34/// fn make_atomic<T: AtomicPrimitive>(val: T) -> T::Atomic {
35///     T::Atomic::new(val)
36/// }
37/// ```
38///
39/// [`core::sync::atomic::AtomicPrimitive`]: https://doc.rust-lang.org/core/sync/atomic/trait.AtomicPrimitive.html
40pub trait AtomicPrimitive: Sized + Copy + Send + Sync {
41    /// The atomic type corresponding to this primitive type.
42    type Atomic: PrimitiveAtomic<Value = Self>;
43
44    /// Converts this value to its atomic counterpart.
45    #[inline]
46    fn to_atomic(self) -> Self::Atomic {
47        Self::Atomic::new(self)
48    }
49}
50
51/// Type alias for the atomic version of a primitive type.
52///
53/// This mirrors the unstable [`core::sync::atomic::Atomic`] type alias.
54///
55/// [`core::sync::atomic::Atomic`]: https://doc.rust-lang.org/core/sync/atomic/type.Atomic.html
56pub type Atomic<T> = <T as AtomicPrimitive>::Atomic;
57
58macro_rules! impl_atomic_primitive {
59    ($($Primitive:ty => $AtomicType:ty),+ $(,)?) => {$(
60        impl AtomicPrimitive for $Primitive {
61            type Atomic = $AtomicType;
62        }
63    )+};
64}
65
66use core::sync::atomic::{
67    AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicIsize, AtomicU8, AtomicU16,
68    AtomicU32, AtomicU64, AtomicUsize,
69};
70
71impl_atomic_primitive! {
72    bool => AtomicBool,
73    u8 => AtomicU8,
74    u16 => AtomicU16,
75    u32 => AtomicU32,
76    u64 => AtomicU64,
77    usize => AtomicUsize,
78    i8 => AtomicI8,
79    i16 => AtomicI16,
80    i32 => AtomicI32,
81    i64 => AtomicI64,
82    isize => AtomicIsize,
83}