1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! Traits for atomic implementations. You probably do not need to worry about
//! this module.

use std::sync::atomic::{
    self, Ordering,
};
use super::{Atom, AtomLogic, AtomInteger};


// ===============================================================================================
// ===== All `Atomic*Impl` traits and `PrimitiveAtom`
// ===============================================================================================

mod sealed {
    /// You cannot implement this trait. That is the point.
    pub trait Sealed {}
}

/// Primitive types that can directly be used in an atomic way.
///
/// This trait is implemented exactly for every type that has a corresponding
/// atomic type in `std::sync::atomic`. You cannot implement this trait for
/// your own types; see [`Atom`] instead.
pub trait PrimitiveAtom: Sized + Copy + sealed::Sealed {
    /// The standard library type that is the atomic version of `Self`.
    type Impl: AtomicImpl<Inner = Self>;
}

/// Common interface of all atomic types in `std::sync::atomic`.
///
/// This trait is exactly implemented for all atomic types in
/// `std::sync::atomic` and you cannot and should not implement this trait for
/// your own types. Instead of using these methods directly, use
/// [`Atomic`][super::Atomic] which has the same interface.
pub trait AtomicImpl: Sized + sealed::Sealed {
    type Inner: PrimitiveAtom<Impl = Self>;

    fn new(v: Self::Inner) -> Self;
    fn get_mut(&mut self) -> &mut Self::Inner;
    fn into_inner(self) -> Self::Inner;
    fn load(&self, order: Ordering) -> Self::Inner;
    fn store(&self, v: Self::Inner, order: Ordering);

    #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
    fn swap(&self, v: Self::Inner, order: Ordering) -> Self::Inner;

    #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
    fn compare_and_swap(
        &self,
        current: Self::Inner,
        new: Self::Inner,
        order: Ordering,
    ) -> Self::Inner;

    #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
    fn compare_exchange(
        &self,
        current: Self::Inner,
        new: Self::Inner,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Self::Inner, Self::Inner>;

    #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
    fn compare_exchange_weak(
        &self,
        current: Self::Inner,
        new: Self::Inner,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Self::Inner, Self::Inner>;
}

/// Atomic types from `std::sync::atomic` which support logical operations.
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
pub trait AtomicLogicImpl: AtomicImpl {
    fn fetch_and(&self, val: Self::Inner, order: Ordering) -> Self::Inner;
    fn fetch_nand(&self, val: Self::Inner, order: Ordering) -> Self::Inner;
    fn fetch_or(&self, val: Self::Inner, order: Ordering) -> Self::Inner;
    fn fetch_xor(&self, val: Self::Inner, order: Ordering) -> Self::Inner;
}

/// Atomic types from `std::sync::atomic` which support integer operations.
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
pub trait AtomicIntegerImpl: AtomicImpl {
    fn fetch_add(&self, val: Self::Inner, order: Ordering) -> Self::Inner;
    fn fetch_sub(&self, val: Self::Inner, order: Ordering) -> Self::Inner;

    #[cfg(feature = "nightly")]
    fn fetch_max(&self, val: Self::Inner, order: Ordering) -> Self::Inner;
    #[cfg(feature = "nightly")]
    fn fetch_min(&self, val: Self::Inner, order: Ordering) -> Self::Inner;

    #[cfg(feature = "nightly")]
    fn fetch_update<F>(
        &self,
        f: F,
        fetch_order: Ordering,
        set_order: Ordering
    ) -> Result<Self::Inner, Self::Inner>
    where
        F: FnMut(Self::Inner) -> Option<Self::Inner>;
}



// ===============================================================================================
// ===== Implementations for standard library types
// ===============================================================================================

/// Expands to the `pack` and `unpack` methods implemented as ID function.
macro_rules! id_pack_unpack {
    () => {
        fn pack(self) -> Self::Repr {
            self
        }
        fn unpack(src: Self::Repr) -> Self {
            src
        }
    };
}

/// Expands to all methods from `AtomicImpl`, each forwarding to
/// `self.that_method`.
macro_rules! pass_through_methods {
    ($ty:ty) => {
        #[inline(always)]
        fn new(v: Self::Inner) -> Self {
            <$ty>::new(v)
        }

        #[inline(always)]
        fn get_mut(&mut self) -> &mut Self::Inner {
            self.get_mut()
        }

        #[inline(always)]
        fn into_inner(self) -> Self::Inner {
            self.into_inner()
        }

        #[inline(always)]
        fn load(&self, order: Ordering) -> Self::Inner {
            self.load(order)
        }

        #[inline(always)]
        fn store(&self, v: Self::Inner, order: Ordering) {
            self.store(v, order)
        }

        #[inline(always)]
        #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
        fn swap(&self, v: Self::Inner, order: Ordering) -> Self::Inner {
            self.swap(v, order)
        }

        #[inline(always)]
        #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
        fn compare_and_swap(
            &self,
            current: Self::Inner,
            new: Self::Inner,
            order: Ordering,
        ) -> Self::Inner {
            self.compare_and_swap(current, new, order)
        }

        #[inline(always)]
        #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
        fn compare_exchange(
            &self,
            current: Self::Inner,
            new: Self::Inner,
            success: Ordering,
            failure: Ordering,
        ) -> Result<Self::Inner, Self::Inner> {
            self.compare_exchange(current, new, success, failure)
        }

        #[inline(always)]
        #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
        fn compare_exchange_weak(
            &self,
            current: Self::Inner,
            new: Self::Inner,
            success: Ordering,
            failure: Ordering,
        ) -> Result<Self::Inner, Self::Inner> {
            self.compare_exchange_weak(current, new, success, failure)
        }
    };
}

/// Expands to all methods from `AtomicLogicImpl`, each forwarding to
/// `self.that_method`.
macro_rules! logical_pass_through_methods {
    () => {
        #[inline(always)]
        fn fetch_and(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_and(val, order)
        }

        #[inline(always)]
        fn fetch_nand(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_nand(val, order)
        }

        #[inline(always)]
        fn fetch_or(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_or(val, order)
        }

        #[inline(always)]
        fn fetch_xor(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_xor(val, order)
        }
    };
}

/// Expands to all methods from `AtomicIntegerImpl`, each forwarding to
/// `self.that_method`.
macro_rules! integer_pass_through_methods {
    () => {
        #[inline(always)]
        fn fetch_add(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_add(val, order)
        }

        #[inline(always)]
        fn fetch_sub(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_sub(val, order)
        }

        /// This method is currently unstable and thus only available when
        /// compiling this crate with the `"nightly"` feature.
        #[cfg(feature = "nightly")]
        fn fetch_max(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_max(val, order)
        }

        /// This method is currently unstable and thus only available when
        /// compiling this crate with the `"nightly"` feature.
        #[cfg(feature = "nightly")]
        fn fetch_min(&self, val: Self::Inner, order: Ordering) -> Self::Inner {
            self.fetch_min(val, order)
        }

        /// This method is currently unstable and thus only available when
        /// compiling this crate with the `"nightly"` feature.
        #[cfg(feature = "nightly")]
        fn fetch_update<F>(
            &self,
            f: F,
            fetch_order: Ordering,
            set_order: Ordering
        ) -> Result<Self::Inner, Self::Inner>
        where
            F: FnMut(Self::Inner) -> Option<Self::Inner>
        {
            self.fetch_update(f, fetch_order, set_order)
        }
    };
}

// ----- `*mut T` and `AtomicPtr` -----
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
impl<T> Atom for *mut T {
    type Repr = Self;
    id_pack_unpack!();
}

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
impl<T> sealed::Sealed for *mut T {}
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
impl<T> PrimitiveAtom for *mut T {
    type Impl = atomic::AtomicPtr<T>;
}

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
impl<T> sealed::Sealed for atomic::AtomicPtr<T> {}
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
impl<T> AtomicImpl for atomic::AtomicPtr<T> {
    type Inner = *mut T;
    pass_through_methods!(atomic::AtomicPtr<T>);
}


// ----- Integers and `bool` -----

macro_rules! impl_std_atomics {
    ($ty:ty, $impl_ty:ident, $is_int:ident) => {
        impl Atom for $ty {
            type Repr = Self;
            id_pack_unpack!();
        }

        impl sealed::Sealed for $ty {}
        impl PrimitiveAtom for $ty {
            type Impl = atomic::$impl_ty;
        }

        impl AtomLogic for $ty {}

        impl sealed::Sealed for atomic::$impl_ty {}
        impl AtomicImpl for atomic::$impl_ty {
            type Inner = $ty;
            pass_through_methods!(atomic::$impl_ty);
        }

        #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
        impl AtomicLogicImpl for atomic::$impl_ty {
            logical_pass_through_methods!();
        }

        #[cfg_attr(feature = "nightly", cfg(target_has_atomic = "cas"))]
        impl_std_atomics!(@int_methods $ty, $impl_ty, $is_int);
    };
    (@int_methods $ty:ty, $impl_ty:ident, true) => {
        impl AtomInteger for $ty {}

        impl AtomicIntegerImpl for atomic::$impl_ty {
            integer_pass_through_methods!();
        }
    };
    (@int_methods $ty:ty, $impl_ty:ident, false) => {};
}

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "8"))]
impl_std_atomics!(bool, AtomicBool, false);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "8"))]
impl_std_atomics!(u8, AtomicU8, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "8"))]
impl_std_atomics!(i8, AtomicI8, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "16"))]
impl_std_atomics!(u16, AtomicU16, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "16"))]
impl_std_atomics!(i16, AtomicI16, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "32"))]
impl_std_atomics!(u32, AtomicU32, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "32"))]
impl_std_atomics!(i32, AtomicI32, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "64"))]
impl_std_atomics!(u64, AtomicU64, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "64"))]
impl_std_atomics!(i64, AtomicI64, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
impl_std_atomics!(usize, AtomicUsize, true);
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))]
impl_std_atomics!(isize, AtomicIsize, true);

// ----- Implementations for non-atomic primitive types ------------------------------------------
#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "32"))]
impl Atom for f32 {
    type Repr = u32;
    fn pack(self) -> Self::Repr {
        self.to_bits()
    }
    fn unpack(src: Self::Repr) -> Self {
        Self::from_bits(src)
    }
}

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "64"))]
impl Atom for f64 {
    type Repr = u64;
    fn pack(self) -> Self::Repr {
        self.to_bits()
    }
    fn unpack(src: Self::Repr) -> Self {
        Self::from_bits(src)
    }
}

#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "32"))]
impl Atom for char {
    type Repr = u32;
    fn pack(self) -> Self::Repr {
        self.into()
    }
    fn unpack(src: Self::Repr) -> Self {
        use std::convert::TryFrom;
        Self::try_from(src).expect("invalid value in <char as Atom>::unpack")
    }
}