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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at http://rust-lang.org/COPYRIGHT.
//
// Copyright 2017 Vadzim Dambrouski, initial port to MSP430.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Atomic types
//!
//! Atomic types provide primitive shared-memory communication between
//! threads, and are the building blocks of other concurrent
//! types.
//!
//! This module defines atomic versions of a select number of primitive
//! types, including [`AtomicBool`], [`AtomicIsize`], and [`AtomicUsize`].
//! Atomic types present operations that, when used correctly, synchronize
//! updates between threads.
//!
//! [`AtomicBool`]: struct.AtomicBool.html
//! [`AtomicIsize`]: struct.AtomicIsize.html
//! [`AtomicUsize`]: struct.AtomicUsize.html
//!
//! MSP430 note: All atomic operations in this crate have `SeqCst`
//! memory [ordering].
//!
//! [ordering]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html
//!
//! Atomic variables are safe to share between threads (they implement [`Sync`])
//! but they do not themselves provide the mechanism for sharing and follow the
//! [threading model](https://doc.rust-lang.org/std/thread/#the-threading-model)
//! of rust.
//!
//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html
//!
//! Most atomic types may be stored in static variables, initialized using
//! the provided static initializers like [`ATOMIC_BOOL_INIT`]. Atomic statics
//! are often used for lazy global initialization.
//!
//! [`ATOMIC_BOOL_INIT`]: constant.ATOMIC_BOOL_INIT.html
//!
//! # Examples
//!
//! A simple spinlock:
//!
//! ```
//! use msp430_atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
//! use std::thread;
//!
//! // Initialize SPINLOCK to 0
//! static SPINLOCK: AtomicUsize = ATOMIC_USIZE_INIT;
//!
//! fn main() {
//!     let thread = thread::spawn(move|| {
//!         SPINLOCK.store(1);
//!     });
//!
//!     // Wait for the other thread to release the lock
//!     while SPINLOCK.load() == 0 {}
//!
//!     if let Err(panic) = thread.join() {
//!         println!("Thread had an error: {:?}", panic);
//!     }
//! }
//! ```

#![no_std]
#![cfg_attr(target_arch = "msp430", feature(asm_experimental_arch))]

#[cfg(target_arch = "msp430")]
use core::arch::asm;
use core::cell::UnsafeCell;
use core::fmt;

/// A boolean type which can be safely shared between threads.
///
/// This type has the same in-memory representation as a `bool`.
#[repr(C, align(1))]
pub struct AtomicBool {
    v: UnsafeCell<u8>,
}

impl Default for AtomicBool {
    /// Creates an `AtomicBool` initialized to `false`.
    fn default() -> Self {
        Self::new(false)
    }
}

// Send is implicitly implemented for AtomicBool.
unsafe impl Sync for AtomicBool {}

/// A raw pointer type which can be safely shared between threads.
///
/// This type has the same in-memory representation as a `*mut T`.
#[cfg_attr(target_pointer_width = "16", repr(C, align(2)))]
#[cfg_attr(target_pointer_width = "32", repr(C, align(4)))]
#[cfg_attr(target_pointer_width = "64", repr(C, align(8)))]
pub struct AtomicPtr<T> {
    p: UnsafeCell<*mut T>,
}

impl<T> Default for AtomicPtr<T> {
    /// Creates a null `AtomicPtr<T>`.
    fn default() -> AtomicPtr<T> {
        AtomicPtr::new(core::ptr::null_mut())
    }
}

unsafe impl<T> Send for AtomicPtr<T> {}
unsafe impl<T> Sync for AtomicPtr<T> {}

/// An [`AtomicBool`] initialized to `false`.
///
/// [`AtomicBool`]: struct.AtomicBool.html
pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);

impl AtomicBool {
    /// Creates a new `AtomicBool`.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let atomic_true  = AtomicBool::new(true);
    /// let atomic_false = AtomicBool::new(false);
    /// ```
    #[inline]
    pub const fn new(v: bool) -> AtomicBool {
        AtomicBool {
            v: UnsafeCell::new(v as u8),
        }
    }

    /// Returns a mutable reference to the underlying `bool`.
    ///
    /// This is safe because the mutable reference guarantees that no other threads are
    /// concurrently accessing the atomic data.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let mut some_bool = AtomicBool::new(true);
    /// assert_eq!(*some_bool.get_mut(), true);
    /// *some_bool.get_mut() = false;
    /// assert_eq!(some_bool.load(), false);
    /// ```
    #[inline]
    pub fn get_mut(&mut self) -> &mut bool {
        unsafe { &mut *(self.v.get() as *mut bool) }
    }

    /// Consumes the atomic and returns the contained value.
    ///
    /// This is safe because passing `self` by value guarantees that no other threads are
    /// concurrently accessing the atomic data.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let some_bool = AtomicBool::new(true);
    /// assert_eq!(some_bool.into_inner(), true);
    /// ```
    #[inline]
    pub fn into_inner(self) -> bool {
        self.v.into_inner() != 0
    }

    /// Loads a value from the bool.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let some_bool = AtomicBool::new(true);
    ///
    /// assert_eq!(some_bool.load(), true);
    /// ```
    #[inline]
    pub fn load(&self) -> bool {
        unsafe { u8::atomic_load(self.v.get()) != 0 }
    }

    /// Stores a value into the bool.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let some_bool = AtomicBool::new(true);
    ///
    /// some_bool.store(false);
    /// assert_eq!(some_bool.load(), false);
    /// ```
    #[inline]
    pub fn store(&self, val: bool) {
        unsafe {
            u8::atomic_store(self.v.get(), val as u8);
        }
    }

    /// Logical "and" with a boolean value.
    ///
    /// Performs a logical "and" operation on the current value and the argument `val`, and sets
    /// the new value to the result.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.and(false);
    /// assert_eq!(foo.load(), false);
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.and(true);
    /// assert_eq!(foo.load(), true);
    ///
    /// let foo = AtomicBool::new(false);
    /// foo.and(false);
    /// assert_eq!(foo.load(), false);
    /// ```
    #[inline]
    pub fn and(&self, val: bool) {
        unsafe { u8::atomic_and(self.v.get(), val as u8) }
    }

    /// Logical "nand" with a boolean value.
    ///
    /// Performs a logical "nand" operation on the current value and the argument `val`, and sets
    /// the new value to the result.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.nand(false);
    /// assert_eq!(foo.load(), true);
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.nand(true);
    /// assert_eq!(foo.load() as usize, 0);
    /// assert_eq!(foo.load(), false);
    ///
    /// let foo = AtomicBool::new(false);
    /// foo.nand(false);
    /// assert_eq!(foo.load(), true);
    /// ```
    #[inline]
    pub fn nand(&self, val: bool) {
        // We can't use atomic_nand here because it can result in a bool with
        // an invalid value. This happens because the atomic operation is done
        // with an 8-bit integer internally, which would set the upper 7 bits.
        // So we just use xor or swap instead.
        if val {
            // !(x & true) == !x
            // We must invert the bool.
            self.xor(true)
        } else {
            // !(x & false) == true
            // We must set the bool to true.
            self.store(true)
        }
    }

    /// Logical "or" with a boolean value.
    ///
    /// Performs a logical "or" operation on the current value and the argument `val`, and sets the
    /// new value to the result.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.or(false);
    /// assert_eq!(foo.load(), true);
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.or(true);
    /// assert_eq!(foo.load(), true);
    ///
    /// let foo = AtomicBool::new(false);
    /// foo.or(false);
    /// assert_eq!(foo.load(), false);
    /// ```
    #[inline]
    pub fn or(&self, val: bool) {
        unsafe { u8::atomic_or(self.v.get(), val as u8) }
    }

    /// Logical "xor" with a boolean value.
    ///
    /// Performs a logical "xor" operation on the current value and the argument `val`, and sets
    /// the new value to the result.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicBool;
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.xor(false);
    /// assert_eq!(foo.load(), true);
    ///
    /// let foo = AtomicBool::new(true);
    /// foo.xor(true);
    /// assert_eq!(foo.load(), false);
    ///
    /// let foo = AtomicBool::new(false);
    /// foo.xor(false);
    /// assert_eq!(foo.load(), false);
    /// ```
    #[inline]
    pub fn xor(&self, val: bool) {
        unsafe { u8::atomic_xor(self.v.get(), val as u8) }
    }
}

impl<T> AtomicPtr<T> {
    /// Creates a new `AtomicPtr`.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicPtr;
    ///
    /// let ptr = &mut 5;
    /// let atomic_ptr  = AtomicPtr::new(ptr);
    /// ```
    #[inline]
    pub const fn new(p: *mut T) -> AtomicPtr<T> {
        AtomicPtr {
            p: UnsafeCell::new(p),
        }
    }

    /// Returns a mutable reference to the underlying pointer.
    ///
    /// This is safe because the mutable reference guarantees that no other threads are
    /// concurrently accessing the atomic data.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicPtr;
    ///
    /// let mut atomic_ptr = AtomicPtr::new(&mut 10);
    /// *atomic_ptr.get_mut() = &mut 5;
    /// assert_eq!(unsafe { *atomic_ptr.load() }, 5);
    /// ```
    #[inline]
    pub fn get_mut(&mut self) -> &mut *mut T {
        unsafe { &mut *self.p.get() }
    }

    /// Consumes the atomic and returns the contained value.
    ///
    /// This is safe because passing `self` by value guarantees that no other threads are
    /// concurrently accessing the atomic data.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicPtr;
    ///
    /// let atomic_ptr = AtomicPtr::new(&mut 5);
    /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
    /// ```
    #[inline]
    pub fn into_inner(self) -> *mut T {
        self.p.into_inner()
    }

    /// Loads a value from the pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicPtr;
    ///
    /// let ptr = &mut 5;
    /// let some_ptr  = AtomicPtr::new(ptr);
    ///
    /// let value = some_ptr.load();
    /// ```
    #[inline]
    pub fn load(&self) -> *mut T {
        unsafe { usize::atomic_load(self.p.get() as *mut usize) as *mut T }
    }

    /// Stores a value into the pointer.
    ///
    /// # Examples
    ///
    /// ```
    /// use msp430_atomic::AtomicPtr;
    ///
    /// let ptr = &mut 5;
    /// let some_ptr  = AtomicPtr::new(ptr);
    ///
    /// let other_ptr = &mut 10;
    ///
    /// some_ptr.store(other_ptr);
    /// ```
    #[inline]
    pub fn store(&self, ptr: *mut T) {
        unsafe {
            usize::atomic_store(self.p.get() as *mut usize, ptr as usize);
        }
    }
}

macro_rules! atomic_int {
    ($int_type:ident $atomic_type:ident $atomic_init:ident $asm_suffix:literal $align:literal) => {
        /// An integer type which can be safely shared between threads.
        ///
        /// This type has the same in-memory representation as the underlying integer type.
        #[repr(C, align($align))]
        pub struct $atomic_type {
            v: UnsafeCell<$int_type>,
        }

        /// An atomic integer initialized to `0`.
        pub const $atomic_init: $atomic_type = $atomic_type::new(0);

        impl Default for $atomic_type {
            fn default() -> Self {
                Self::new(Default::default())
            }
        }

        impl fmt::Debug for $atomic_type {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.debug_tuple(stringify!($atomic_type))
                 .field(&self.load())
                 .finish()
            }
        }

        // Send is implicitly implemented.
        unsafe impl Sync for $atomic_type {}

        impl $atomic_type {
            /// Creates a new atomic integer.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let atomic_forty_two  = AtomicIsize::new(42);
            /// ```
            #[inline]
            pub const fn new(v: $int_type) -> Self {
                $atomic_type {v: UnsafeCell::new(v)}
            }

            /// Returns a mutable reference to the underlying integer.
            ///
            /// This is safe because the mutable reference guarantees that no other threads are
            /// concurrently accessing the atomic data.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let mut some_isize = AtomicIsize::new(10);
            /// assert_eq!(*some_isize.get_mut(), 10);
            /// *some_isize.get_mut() = 5;
            /// assert_eq!(some_isize.load(), 5);
            /// ```
            #[inline]
            pub fn get_mut(&mut self) -> &mut $int_type {
                unsafe { &mut *self.v.get() }
            }

            /// Consumes the atomic and returns the contained value.
            ///
            /// This is safe because passing `self` by value guarantees that no other threads are
            /// concurrently accessing the atomic data.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let some_isize = AtomicIsize::new(5);
            /// assert_eq!(some_isize.into_inner(), 5);
            /// ```
            #[inline]
            pub fn into_inner(self) -> $int_type {
                 self.v.into_inner()
            }

            /// Loads a value from the atomic integer.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let some_isize = AtomicIsize::new(5);
            ///
            /// assert_eq!(some_isize.load(), 5);
            /// ```
            #[inline]
            pub fn load(&self) -> $int_type {
                unsafe { $int_type::atomic_load(self.v.get()) }
            }

            /// Stores a value into the atomic integer.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let some_isize = AtomicIsize::new(5);
            ///
            /// some_isize.store(10);
            /// assert_eq!(some_isize.load(), 10);
            /// ```
            #[inline]
            pub fn store(&self, val: $int_type) {
                unsafe { $int_type::atomic_store(self.v.get(), val); }
            }

            /// Adds to the current value, returning the previous value.
            ///
            /// This operation wraps around on overflow.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let foo = AtomicIsize::new(0);
            /// foo.add(10);
            /// assert_eq!(foo.load(), 10);
            /// ```
            #[inline]
            pub fn add(&self, val: $int_type) {
                unsafe { $int_type::atomic_add(self.v.get(), val) }
            }

            /// Subtracts from the current value, returning the previous value.
            ///
            /// This operation wraps around on overflow.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let foo = AtomicIsize::new(0);
            /// foo.sub(10);
            /// assert_eq!(foo.load(), -10);
            /// ```
            #[inline]
            pub fn sub(&self, val: $int_type) {
                unsafe { $int_type::atomic_sub(self.v.get(), val) }
            }

            /// Bitwise "and" with the current value.
            ///
            /// Performs a bitwise "and" operation on the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let foo = AtomicIsize::new(0b101101);
            /// foo.and(0b110011);
            /// assert_eq!(foo.load(), 0b100001);
            #[inline]
            pub fn and(&self, val: $int_type) {
                unsafe { $int_type::atomic_and(self.v.get(), val) }
            }

            /// Bitwise "or" with the current value.
            ///
            /// Performs a bitwise "or" operation on the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let foo = AtomicIsize::new(0b101101);
            /// foo.or(0b110011);
            /// assert_eq!(foo.load(), 0b111111);
            #[inline]
            pub fn or(&self, val: $int_type) {
                unsafe { $int_type::atomic_or(self.v.get(), val) }
            }

            /// Bitwise "xor" with the current value.
            ///
            /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
            /// sets the new value to the result.
            ///
            /// # Examples
            ///
            /// ```
            /// use msp430_atomic::AtomicIsize;
            ///
            /// let foo = AtomicIsize::new(0b101101);
            /// foo.xor(0b110011);
            /// assert_eq!(foo.load(), 0b011110);
            #[inline]
            pub fn xor(&self, val: $int_type) {
                unsafe { $int_type::atomic_xor(self.v.get(), val) }
            }
        }

        #[cfg(target_arch = "msp430")]
        impl AtomicOperations for $int_type {
            #[inline(always)]
            unsafe fn atomic_store(dst: *mut Self, val: Self) {
                asm!(concat!("mov", $asm_suffix, " {1}, 0({0})"), in(reg) dst, in(reg) val);
            }

            #[inline(always)]
            unsafe fn atomic_load(dst: *const Self) -> Self {
                let out;
                asm!(concat!("mov", $asm_suffix, " @{0}, {1}"), in(reg) dst, lateout(reg) out);
                out
            }

            #[inline(always)]
            unsafe fn atomic_add(dst: *mut Self, val: Self) {
                asm!(concat!("add", $asm_suffix, " {1}, 0({0})"), in(reg) dst, in(reg) val);
            }

            #[inline(always)]
            unsafe fn atomic_sub(dst: *mut Self, val: Self) {
                asm!(concat!("sub", $asm_suffix, " {1}, 0({0})"), in(reg) dst, in(reg) val);
            }

            #[inline(always)]
            unsafe fn atomic_and(dst: *mut Self, val: Self) {
                asm!(concat!("and", $asm_suffix, " {1}, 0({0})"), in(reg) dst, in(reg) val);
            }

            #[inline(always)]
            unsafe fn atomic_clear(dst: *mut Self, val: Self) {
                asm!(concat!("bic", $asm_suffix, " {1}, 0({0})"), in(reg) dst, in(reg) val);
            }

            #[inline(always)]
            unsafe fn atomic_or(dst: *mut Self, val: Self) {
                asm!(concat!("bis", $asm_suffix, " {1}, 0({0})"), in(reg) dst, in(reg) val);
            }

            #[inline(always)]
            unsafe fn atomic_xor(dst: *mut Self, val: Self) {
                asm!(concat!("xor", $asm_suffix, " {1}, 0({0})"), in(reg) dst, in(reg) val);
            }
        }

        #[cfg(not(target_arch = "msp430"))]
        impl AtomicOperations for $int_type {
            #[inline(always)]
            unsafe fn atomic_store(dst: *mut Self, val: Self) {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .store(val, ::core::sync::atomic::Ordering::SeqCst);
            }

            #[inline(always)]
            unsafe fn atomic_load(dst: *const Self) -> Self {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .load(::core::sync::atomic::Ordering::SeqCst)
            }

            #[inline(always)]
            unsafe fn atomic_add(dst: *mut Self, val: Self) {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .fetch_add(val, ::core::sync::atomic::Ordering::SeqCst);
            }

            #[inline(always)]
            unsafe fn atomic_sub(dst: *mut Self, val: Self) {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .fetch_sub(val, ::core::sync::atomic::Ordering::SeqCst);
            }

            #[inline(always)]
            unsafe fn atomic_and(dst: *mut Self, val: Self) {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .fetch_and(val, ::core::sync::atomic::Ordering::SeqCst);
            }

            #[inline(always)]
            unsafe fn atomic_clear(dst: *mut Self, val: Self) {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .fetch_and(!val, ::core::sync::atomic::Ordering::SeqCst);
            }

            #[inline(always)]
            unsafe fn atomic_or(dst: *mut Self, val: Self) {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .fetch_or(val, ::core::sync::atomic::Ordering::SeqCst);
            }

            #[inline(always)]
            unsafe fn atomic_xor(dst: *mut Self, val: Self) {
                (*(dst as *const ::core::sync::atomic::$atomic_type))
                    .fetch_xor(val, ::core::sync::atomic::Ordering::SeqCst);
            }
        }
    }
}

atomic_int! {
    i8 AtomicI8 ATOMIC_I8_INIT ".b" 1
}

atomic_int! {
    u8 AtomicU8 ATOMIC_U8_INIT ".b" 1
}

atomic_int! {
    i16 AtomicI16 ATOMIC_I16_INIT ".w" 2
}

atomic_int! {
    u16 AtomicU16 ATOMIC_U16_INIT ".w" 2
}

#[cfg(target_pointer_width = "16")]
atomic_int! {
    isize AtomicIsize ATOMIC_ISIZE_INIT ".w" 2
}
#[cfg(target_pointer_width = "32")]
atomic_int! {
    isize AtomicIsize ATOMIC_ISIZE_INIT ".w" 4
}
#[cfg(target_pointer_width = "64")]
atomic_int! {
    isize AtomicIsize ATOMIC_ISIZE_INIT ".w" 8
}

#[cfg(target_pointer_width = "16")]
atomic_int! {
    usize AtomicUsize ATOMIC_USIZE_INIT ".w" 2
}
#[cfg(target_pointer_width = "32")]
atomic_int! {
    usize AtomicUsize ATOMIC_USIZE_INIT ".w" 4
}
#[cfg(target_pointer_width = "64")]
atomic_int! {
    usize AtomicUsize ATOMIC_USIZE_INIT ".w" 8
}

/// Atomic arithmetic and bitwise operations implemented for numerical types. Each operation is
/// implemented with a single assembly instruction.
pub trait AtomicOperations {
    /// Store value into destination pointee.
    unsafe fn atomic_store(dst: *mut Self, val: Self);
    /// Read value from destination pointee.
    unsafe fn atomic_load(dst: *const Self) -> Self;
    /// Add value to destination pointee. Result may wrap around.
    unsafe fn atomic_add(dst: *mut Self, val: Self);
    /// Subtract value from destination pointee. Result may wrap around.
    unsafe fn atomic_sub(dst: *mut Self, val: Self);
    /// Clear all bits in destination pointee that are zeroed in value.
    unsafe fn atomic_and(dst: *mut Self, val: Self);
    /// Clear all bits in destination pointee that are set in value
    unsafe fn atomic_clear(dst: *mut Self, val: Self);
    /// Set all bits in destination pointee that are set in value.
    unsafe fn atomic_or(dst: *mut Self, val: Self);
    /// Toggle all bits in destination pointee that are set in value.
    unsafe fn atomic_xor(dst: *mut Self, val: Self);
}

impl fmt::Debug for AtomicBool {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("AtomicBool").field(&self.load()).finish()
    }
}

impl<T> fmt::Debug for AtomicPtr<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("AtomicPtr").field(&self.load()).finish()
    }
}