ecmascript_atomics 0.1.3

ECMAScript and Java memory model racy atomics.
Documentation
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Copyright of the originating code is owned by Firefox authors and Mozilla,
// modifications by Aapo Alasuutari.

#![no_std]

//! # Racy atomic operations
//!
//! This library provides atomic operations that match the ECMAScript
//! specification's memory model: this is effectively the same memory model as
//! Java's shared variables model. This model allows non-atomic reads and
//! writes to perform data races, and also allows mixed-size atomic reads and
//! writes. Both of these are undefined behaviour in the C++/Rust memory model,
//! which is why these atomic operations are implemented using inline assembly.
//!
//! The contents of the library are copied and adapted from Mozilla Firefox's
//! source code, basing mainly on [GenerateAtomicOperations.py].
//!
//! The fundamental constraints on the functions are:
//!
//! - That any Atomic operations performed on memory used in these
//!   functions must only be accessed using these functions or functions
//!   that have a compatible realisation. Importantly, it is strictly
//!   undefined behaviour to use normal Rust Atomics in conjunction with
//!   the racy atomic operations in this library.
//!
//! - That accesses may race without creating C++/Rust undefined behavior:
//!   atomic accesses (marked "SeqCst") may race with non-atomic
//!   accesses (marked "Unordered"); overlapping but non-matching,
//!   and hence incompatible, atomic accesses may race; and non-atomic
//!   accesses may race. The effects of races need not be predictable,
//!   so garbage can be produced by a read or written by a write, but
//!   the effects must be benign: the program must continue to run, and
//!   only the memory in the union of addresses named in the racing
//!   accesses may be affected.
//!
//! The compatibility constraint means that if the memory is accessed elsewhere
//! then it must make compatible decisions about how to implement atomic
//! operations with the functions below.
//!
//! The safe-for-races constraint means that by and large, it is hard or
//! impossible to implement these primitives in C++/Rust. See "Implementation
//! notes" below.
//!
//! The "SeqCst" suffix on operations means "sequentially consistent"
//! and means such a function's operation must have "sequentially
//! consistent" memory ordering. This corresponds with the Rust Atomics'
//! "SeqCst" ordering.
//!
//! Note that an "Unordered" access does not provide the atomicity of
//! a "relaxed atomic" access: it can read or write garbage if there's
//! a race.
//!
//!
//! ## Implementation notes.
//!
//! It's not a requirement that these functions be inlined.
//!
//! In principle these functions will not be written in Rust, thus
//! making races defined behavior if all racy accesses from Rust go via
//! these functions.
//!
//! The appropriate implementations will be platform-specific and
//! there are some obvious implementation strategies to choose
//! from, sometimes a combination is appropriate:
//!
//!  - generating the code at run-time with a JIT;
//!  - hand-written assembler (maybe inline); or
//!  - using special compiler intrinsics or directives.
//!
//! Trusting the compiler not to generate code that blows up on a
//! race definitely won't work in the presence of TSan, or even of
//! optimizing compilers in seemingly-"innocuous" conditions. (See
//! https://www.usenix.org/legacy/event/hotpar11/tech/final_files/Boehm.pdf
//! for details.)
//!
//! [GenerateAtomicOperations.py]: https://searchfox.org/firefox-main/source/js/src/jit/GenerateAtomicOperations.py

mod generated;
mod unordered_copy;

use core::{
    cell::UnsafeCell, hint::assert_unchecked, marker::PhantomData, mem::MaybeUninit, ptr::NonNull,
};

use generated::*;
use unordered_copy::*;

use crate::private::Sealed;

/// Public trait for allowing users of the library to name the types that can
/// be natively stored in racy memory. These are effectively the unsigned
/// integers from 1 to 8 bytes in size.
pub trait RacyStorage: Sealed {}

impl RacyStorage for u8 {}
impl RacyStorage for u16 {}
impl RacyStorage for u32 {}
impl RacyStorage for u64 {}
impl RacyStorage for usize {}

/// ECMAScript atomic memory orderings
///
/// Memory orderings specify the way atomic operations synchronise memory.
/// With [`Ordering::Unordered`], no synchronisation is performed. With
/// [`Ordering::SeqCst`], a store-load pair of operations synchronize other
/// memory while additionally preserving a total order of such operations
/// across all threads.
///
/// The ECMAScript memory model is explained in the [ECMAScript Language
/// specification](https://tc39.es/ecma262/#sec-memory-model). Note that the
/// "INIT" ordering is not offered here as all initialisation of the memory
/// should happen before calling the [`enter`] method used to move memory from
/// the Rust memory model over into the ECMAScript memory model.
///
/// [`enter`]: crate::RacyMemory::enter
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum Ordering {
    /// No ordering constraints, stores and loads may tear (ie. are not
    /// necessarily atomic).
    ///
    /// Corresponds to [`Unordered`] in LLVM.
    ///
    /// [`Unordered`]: https://llvm.org/docs/Atomics.html#unordered
    Unordered,
    /// All threads see all seqeuentially consistent operations in the same
    /// order.
    ///
    /// Corresponds to [`SeqCst`] in Rust.
    ///
    /// [`SeqCst`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html#variant.SeqCst
    SeqCst,
}

/// A sequentially consistent atomic fence.
///
/// See [std::sync::atomic::fence] for details.
#[inline(always)]
pub fn fence() {
    core::sync::atomic::fence(core::sync::atomic::Ordering::SeqCst);
}

/// Emits a machine instruction to signal the processor that it is running in a
/// busy-wait spin-loop (“spin lock”).
///
/// See [std::hint::spin_loop] for details.
#[inline(always)]
pub fn atomic_pause() {
    core::hint::spin_loop();
}

/// Opaque handle to a slab of memory with the ECMAScript Atomics memory model.
/// The slab must be created using the [`enter`] method and must be turned back
/// into Rust memory using the [`exit`] method (note; this must be strictly
/// synchronised with all possible users of the racy atomic memory).
///
/// The memory can be freely shared to multiple threads for use and all APIs on
/// the memory are guaranteed to not cause undefined behaviour even when data
/// races or mixed-size atomics are used. Tearing may occur when using the copy
/// APIs, meaning that usage should generally be careful and try to avoid both
/// data races and mixed-size atomics.
///
/// [`enter`]: crate::RacyMemory::enter
/// [`exit`]: crate::RacyMemory::exit
///
/// # Soundness
///
/// The memory behind this handle is not and must not be read as Rust memory.
/// Any Rust reads or writes into the memory are undefined behaviour.
///
/// # Allocations
///
/// The [`enter`] method takes ownership of Rust memory and (conceptually)
/// deallocates it. Therefore, the pointer passed into the method must not be
/// deallocated by the caller. Conversely, the [`exit`] method (conceptually)
/// allocates new Rust memory and returns a pointer to it to the caller. The
/// caller is therefore responsible for deallocating the Rust memory.
///
/// Each `enter` call must be matched by an equal `exit` call on the same
/// slice, lest the ECMAScript memory be leaked.
///
/// [`enter`]: crate::RacyMemory::enter
/// [`exit`]: crate::RacyMemory::exit
pub struct RacyMemory<T: Sealed> {
    ptr: RacyPtr<T>,
    len: usize,
}

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl<T: Sealed> Send for RacyMemory<T> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl<T: Sealed> Sync for RacyMemory<T> {}

impl<T: Sealed> RacyMemory<T> {
    /// Move a memory allocation into the ECMAScript memory model.
    ///
    /// # Safety
    ///
    /// `ptr` must be a pointer to `len` bytes of readable and writable memory.
    ///
    /// # Soundness
    ///
    /// This deallocates the existing memory behind `ptr` (in an abstract
    /// machine sense), such that after this call the `ptr` must be viewed as
    /// an invalid pointer. It is thus strictly forbidden for any Rust code to
    /// read from or write into the memory, including with atomic operations.
    #[inline]
    #[must_use]
    pub unsafe fn enter(ptr: NonNull<u8>, len: usize) -> RacyMemory<u8> {
        let mut ptr = ptr.as_ptr();
        // SAFETY: noop.
        unsafe {
            core::arch::asm!(
                "/* Magic spell: let {} no longer be memory in Rust's eyes! */",
                // Note: ptr is and out parameter so that the assembly block
                // can conceptually deallocate the original ptr, removing its
                // provenance, and return a new ptr with difference provenance.
                inlateout(reg) ptr,
                options(nostack, preserves_flags)
            )
        }
        // SAFETY: Magic spell always returns non-null pointers.
        let ptr = RacyPtr::from_ptr(unsafe { NonNull::new_unchecked(ptr.cast()) });
        RacyMemory::from_raw_parts(ptr, len)
    }

    /// Move a typed memory allocation into the ECMAScript memory model.
    ///
    /// # Safety
    ///
    /// `ptr` must point to a valid, uniquely owned `T`.
    ///
    /// # Soudness
    ///
    /// See [`enter`] for details.
    ///
    /// [`enter`]: crate::RacyMemory::enter
    pub unsafe fn enter_ptr(ptr: NonNull<T>) -> Self {
        let RacyMemory { ptr, .. } = unsafe { Self::enter(ptr.cast(), size_of::<T>()) };
        Self::from_raw_parts(ptr.cast(), 1)
    }

    /// Move a typed memory allocation slice into the ECMAScript memory model.
    ///
    /// # Safety
    ///
    /// `ptr` must point to a valid, uniquely owned `T`.
    ///
    /// # Soudness
    ///
    /// See [`enter`] for details.
    ///
    /// [`enter`]: crate::RacyMemory::enter
    pub unsafe fn enter_slice(ptr: NonNull<[T]>) -> Self {
        let len = ptr.len();
        let RacyMemory { ptr, .. } = unsafe { Self::enter(ptr.cast(), size_of::<T>() * len) };
        Self::from_raw_parts(ptr.cast(), len)
    }

    /// Move an ECMAScript memory model into the void and return a new Rust
    /// memory pointer to `len` bytes.
    ///
    /// # Safety
    ///
    /// This must be the only referrer to the racy atomic memory.
    ///
    /// # Soundness
    ///
    /// This deallocates the ECMAScript memory behind `ptr` (in an abstract
    /// sense). It is thus strictly forbidden to use any racy value derived
    /// from this memory after this call happens, on any thread. This call must
    /// therefore be strictly synchronised between threads, and only one thread
    /// is allowed to perform this call.
    #[inline]
    #[must_use]
    pub unsafe fn exit(self) -> (NonNull<T>, usize) {
        let mut ptr = self.ptr.as_ptr().as_ptr();
        // SAFETY: noop.
        unsafe {
            core::arch::asm!(
                "/* Magic spell: let {} be memory in Rust's eyes! */",
                // Note: ptr is and out parameter so that the assembly block
                // can conceptually deallocate the ECMAScript memory, allocate
                // new Rust memory, and return a pointer to it.
                inlateout(reg) ptr,
                options(nostack, preserves_flags)
            )
        }
        // SAFETY: Magic spell always returns non-null pointers.
        (unsafe { NonNull::new_unchecked(ptr.cast()) }, self.len)
    }

    /// Access the racy atomic memory using a shared slice.
    #[inline(always)]
    pub const fn as_slice(&self) -> RacySlice<'_, T> {
        // SAFETY: type guarantees proper allocation.
        unsafe { RacySlice::from_raw_parts(self.ptr, self.len) }
    }

    /// Destructure a racy atomic memory into raw parts.
    #[inline(always)]
    pub const fn into_raw_parts(self) -> (RacyPtr<T>, usize) {
        (self.ptr, self.len)
    }

    /// Recrate a racy atomic memory slice from raw parts.
    ///
    /// # Safety
    ///
    /// `ptr` must point to a racy atomic memory with a length of exactly `len`
    /// elements and be properly aligned. Note that this function does
    /// not "reallocate" the pointed-to memory.
    pub const fn from_raw_parts(ptr: RacyPtr<T>, len: usize) -> Self {
        Self { ptr, len }
    }
}

mod private {
    pub trait Sealed: Copy + Eq + Send + Sync + core::fmt::Display {}

    impl Sealed for u8 {}
    impl Sealed for u16 {}
    impl Sealed for u32 {}
    impl Sealed for u64 {}
    impl Sealed for usize {}
}

/// Opaque handle to a slice of memory with the ECMAScript Atomics memory
/// model.
///
/// # Soundness
///
/// The memory behind this handle is not and must not be read as Rust memory.
/// Any Rust reads or writes into the memory are undefined behaviour.
#[derive(Clone, Copy)]
pub struct RacySlice<'a, T: Sealed> {
    ptr: RacyPtr<T>,
    len: usize,
    __marker: PhantomData<&'a UnsafeCell<T>>,
}

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl<T: Sealed> Send for RacySlice<'_, T> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl<T: Sealed> Sync for RacySlice<'_, T> {}

impl<'a, T: Sealed> RacySlice<'a, T> {
    /// Destructure a racy atomic memory slice into raw parts.
    #[inline(always)]
    pub const fn into_raw_parts(self) -> (RacyPtr<T>, usize) {
        (self.ptr, self.len)
    }

    /// Create a new racy atomic memory slice from a racy atomic byte pointer
    /// and length.
    ///
    /// # Safety
    ///
    /// `ptr` must point to a racy atomic memory with a length of at least
    /// `len` elements and be properly aligned. Note that this function does
    /// not "reallocate" the pointed-to memory.
    #[inline(always)]
    pub const unsafe fn from_raw_parts(ptr: RacyPtr<T>, len: usize) -> Self {
        Self {
            ptr,
            len,
            __marker: PhantomData,
        }
    }

    const fn as_ptr(&self) -> RacyPtr<T> {
        self.ptr
    }

    /// Returns the number of elements in the slice.
    #[inline(always)]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Return the byte length of the slice.
    const fn byte_length(&self) -> usize {
        // SAFETY: slice is guaranteed to point to len valid items.
        unsafe {
            assert_unchecked(self.len().checked_mul(size_of::<T>()).is_some());
            self.len.unchecked_mul(size_of::<T>())
        }
    }

    /// Returns `true` if the slice has a length of 0.
    #[inline(always)]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Transmutes the racy memory slice to a slice of another racy memory
    /// type, ensuring alignment of the types is maintained.
    ///
    /// This method splits the slice into three distinct slices: prefix,
    /// correctly aligned middle slice of a new type, and the suffix slice. The
    /// middle part will be as big as possible under the given alignment
    /// constraint and element size.
    pub fn align_to<U: Sealed>(self) -> (RacySlice<'a, u8>, RacySlice<'a, U>, RacySlice<'a, u8>) {
        let byte_length = self.byte_length();
        let head_ptr = self.ptr.as_ptr();
        let head_length = head_ptr.align_offset(align_of::<U>()).min(byte_length);
        // SAFETY: does not overflow length.
        let body_ptr = unsafe { head_ptr.byte_add(head_length) };
        let remaining_byte_length = byte_length - head_length;
        let body_length = remaining_byte_length / size_of::<U>();
        let tail_length = remaining_byte_length % size_of::<U>();
        debug_assert_eq!(
            head_length + body_length * size_of::<U>() + tail_length,
            byte_length,
            "align_to produced a collection of slices with different total byte length than original"
        );
        // SAFETY: cannot overflow len as body_length is derived from len.
        let tail_ptr = unsafe { body_ptr.byte_add(body_length * size_of::<U>()) };
        if const { align_of::<U>() <= align_of::<T>() } {
            // SAFETY: optimisation check.
            unsafe {
                assert_unchecked(
                    head_length == 0
                        && tail_length == 0
                        && body_length == byte_length / size_of::<U>(),
                );
            };
        }
        (
            RacySlice {
                ptr: RacyPtr::from_ptr(head_ptr),
                len: head_length,
                __marker: PhantomData,
            },
            RacySlice {
                ptr: RacyPtr::from_ptr(body_ptr),
                len: body_length,
                __marker: PhantomData,
            },
            RacySlice {
                ptr: RacyPtr::from_ptr(tail_ptr),
                len: tail_length,
                __marker: PhantomData,
            },
        )
    }

    /// Transmutes the the racy memory slice to a slice of racy bytes.
    #[inline(always)]
    pub const fn to_bytes(self) -> RacySlice<'a, u8> {
        // SAFETY: Totally safe here.
        unsafe { RacySlice::from_raw_parts(self.as_ptr().cast(), self.byte_length()) }
    }

    /// Create a slice of racy atomic memory starting at the given offset.
    /// Returns an empty slice if the offset is beyond the end of this slice.
    #[inline]
    pub fn slice_from(&self, offset: usize) -> Self {
        // SAFETY: cannot overflow len.
        let ptr = RacyPtr::from_ptr(unsafe {
            self.ptr
                .as_ptr()
                .byte_add(offset.min(self.len) * size_of::<T>())
        });
        let len = self.len.saturating_sub(offset);
        // SAFETY: Guaranteed to be proper.
        unsafe { Self::from_raw_parts(ptr, len) }
    }

    /// Create a slice of racy atomic memory ending at the given offset.
    /// Returns self if the offset is beyond the end of this slice.
    #[inline]
    pub fn slice_to(&self, offset: usize) -> Self {
        let ptr = self.ptr;
        let len = self.len.min(offset);

        // SAFETY: Guaranteed to be proper.
        unsafe { Self::from_raw_parts(ptr, len) }
    }

    /// Create a slice of racy atomic memory with the given offsets, bounded to
    /// the end of this slice.
    #[inline]
    pub fn slice(&self, start: usize, end: usize) -> Self {
        // First bound the offsets within the slice.
        let start = start.min(self.len);
        let end = end.min(self.len);
        // Then calculate the slice length, saturating at 0 if order is reversed.
        let len = end.saturating_sub(start);
        // SAFETY: cannot overflow len.
        let ptr = RacyPtr::from_ptr(unsafe { self.ptr.as_ptr().byte_add(start * size_of::<T>()) });
        // SAFETY: Guaranteed to be proper.
        unsafe { Self::from_raw_parts(ptr, len) }
    }

    /// Load a u8 from the start of this slice using Unordered atomic ordering.
    ///
    /// Returns None if the slice is empty.
    #[inline]
    pub fn load_u8(&self) -> Option<u8> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.is_empty() {
            return None;
        }
        Some(atomic_load_8_unsynchronized(self.ptr.as_ptr()))
    }

    /// Load a u16 from the start of this slice using Unordered atomic
    /// ordering. The slice need not be aligned to the type.
    ///
    /// Returns None if the slice is smaller than 2 bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline]
    pub fn load_u16(&self) -> Option<u16> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < 2 {
            return None;
        }
        if const { align_of::<T>() >= align_of::<u16>() } || UNALIGNED_ACCESS_IS_OK {
            // Always properly aligned.
            return Some(atomic_load_16_unsynchronized(self.ptr.as_ptr()));
        }
        let mut scratch = MaybeUninit::<u16>::uninit();
        let dst = unsafe { NonNull::new_unchecked(scratch.as_mut_ptr().cast::<()>()) };
        // SAFETY: checked self length, dst is proper length.
        unsafe { unordered_memcpy_down_unsynchronized(self.ptr.as_ptr(), dst, 2) };
        // SAFETY: copy has initialised the scratch data.
        Some(unsafe { scratch.assume_init() })
    }

    /// Load a u32 from the start of this slice using Unordered atomic
    /// ordering. The slice need not be aligned to the type.
    ///
    /// Returns None if the slice is smaller than 4 bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline]
    pub fn load_u32(&self) -> Option<u32> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < 4 {
            return None;
        }
        if const { align_of::<T>() >= align_of::<u32>() } || UNALIGNED_ACCESS_IS_OK {
            // Always properly aligned.
            return Some(atomic_load_32_unsynchronized(self.ptr.as_ptr()));
        }
        let mut scratch = MaybeUninit::<u32>::uninit();
        let dst = unsafe { NonNull::new_unchecked(scratch.as_mut_ptr().cast::<()>()) };
        // SAFETY: checked self length, dst is proper length.
        unsafe { unordered_memcpy_down_unsynchronized(self.ptr.as_ptr(), dst, 4) };
        // SAFETY: copy has initialised the scratch data.
        Some(unsafe { scratch.assume_init() })
    }

    /// Load a u64 from the start of this slice using Unordered atomic
    /// ordering. The slice need not be aligned to the type.
    ///
    /// Returns None if the slice is smaller than 8 bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline]
    pub fn load_u64(&self) -> Option<u64> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < 8 {
            return None;
        }
        #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
        if const { align_of::<T>() >= align_of::<u64>() } || UNALIGNED_ACCESS_IS_OK {
            // Always properly aligned.
            return Some(atomic_load_64_unsynchronized(self.ptr.as_ptr()));
        }
        let mut scratch = MaybeUninit::<u64>::uninit();
        let dst = unsafe { NonNull::new_unchecked(scratch.as_mut_ptr().cast::<()>()) };
        // SAFETY: checked self length, dst is proper length.
        unsafe { unordered_memcpy_down_unsynchronized(self.ptr.as_ptr(), dst, 8) };
        // SAFETY: copy has initialised the scratch data.
        Some(unsafe { scratch.assume_init() })
    }

    /// Load a usize from the start of this slice using Unordered atomic
    /// ordering. The slice need not be aligned to the type.
    ///
    /// Returns None if the slice is smaller than `size_of::<usize>()` bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline(always)]
    pub fn load_usize(&self) -> Option<usize> {
        #[cfg(target_pointer_width = "16")]
        {
            self.load_u16().map(|u| u as usize)
        }
        #[cfg(target_pointer_width = "32")]
        {
            self.load_u32().map(|u| u as usize)
        }
        #[cfg(target_pointer_width = "64")]
        {
            self.load_u64().map(|u| u as usize)
        }
    }

    /// Store a u8 into the start of this slice using Unordered atomic ordering
    /// mode.
    ///
    /// Returns None if the slice is empty.
    #[inline]
    pub fn store_u8(&self, val: u8) -> Option<()> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.is_empty() {
            return None;
        }
        atomic_store_8_unsynchronized(self.ptr.as_ptr(), val);
        Some(())
    }

    /// Store a u16 into the start of this slice using Unordered atomic
    /// ordering mode.
    ///
    /// Returns None if the slice is smaller than 2 bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline]
    pub fn store_u16(&self, val: u16) -> Option<()> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < 2 {
            return None;
        }
        if const { align_of::<T>() >= align_of::<u16>() } || UNALIGNED_ACCESS_IS_OK {
            // Always properly aligned.
            return {
                atomic_store_16_unsynchronized(self.ptr.as_ptr(), val);
                Some(())
            };
        }
        // SAFETY: checked self length, dst is proper length.
        let src = unsafe { NonNull::new_unchecked(&val as *const _ as *mut ()) };
        unsafe { unordered_memcpy_down_unsynchronized(src, self.ptr.as_ptr(), 2) };
        Some(())
    }

    /// Store a u32 into the start of this slice using Unordered atomic
    /// ordering mode.
    ///
    /// Returns None if the slice is smaller than 4 bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline]
    pub fn store_u32(&self, val: u32) -> Option<()> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < 4 {
            return None;
        }
        if const { align_of::<T>() >= align_of::<u32>() } || UNALIGNED_ACCESS_IS_OK {
            // Always properly aligned.
            return {
                atomic_store_32_unsynchronized(self.ptr.as_ptr(), val);
                Some(())
            };
        }
        // SAFETY: checked self length, dst is proper length.
        let src = unsafe { NonNull::new_unchecked(&val as *const _ as *mut ()) };
        unsafe { unordered_memcpy_down_unsynchronized(src, self.ptr.as_ptr(), 4) };
        Some(())
    }

    /// Store a u64 into the start of this slice using Unordered atomic
    /// ordering mode.
    ///
    /// Returns None if the slice is smaller than 8 bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline]
    pub fn store_u64(&self, val: u64) -> Option<()> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < 8 {
            return None;
        }
        #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
        if const { align_of::<T>() >= align_of::<u64>() } || UNALIGNED_ACCESS_IS_OK {
            // Always properly aligned.
            return {
                atomic_store_64_unsynchronized(self.ptr.as_ptr(), val);
                Some(())
            };
        }
        // SAFETY: checked self length, dst is proper length.
        let src = unsafe { NonNull::new_unchecked(&val as *const _ as *mut ()) };
        unsafe { unordered_memcpy_down_unsynchronized(src, self.ptr.as_ptr(), 8) };
        Some(())
    }

    /// Store a usize into the start of this slice using Unordered atomic
    /// ordering mode.
    ///
    /// Returns None if the slice is smaller than `size_of::<usize>()` bytes.
    ///
    /// # Tearing
    ///
    /// This load may tear
    #[inline]
    pub fn store_usize(&self, val: usize) -> Option<()> {
        #[cfg(target_pointer_width = "16")]
        {
            self.store_u16(val as u16)
        }
        #[cfg(target_pointer_width = "32")]
        {
            self.store_u32(val as u32)
        }
        #[cfg(target_pointer_width = "64")]
        {
            self.store_u64(val as u64)
        }
    }

    /// Convert the memory into a racy atomic byte at the start of the slice.
    /// Returns None if the slice is smaller than 1 byte.
    #[inline]
    pub fn as_u8(&self) -> Option<RacyU8<'a>> {
        if self.is_empty() {
            None
        } else {
            Some(RacyU8::from_ptr(self.ptr.as_ptr()))
        }
    }

    /// Convert the memory into a racy atomic u16 at the start of the slice.
    /// Returns None if the slice is smaller than 2 bytes in size or is not
    /// correctly aligned.
    #[inline]
    pub fn as_u16(&self) -> Option<RacyU16<'a>> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < size_of::<u16>() || !self.ptr.as_ptr().cast::<u16>().is_aligned() {
            None
        } else {
            Some(RacyU16::from_ptr(self.ptr.as_ptr()))
        }
    }

    /// Convert the memory into a racy atomic u32 at the start of the slice.
    /// Returns None if the slice is smaller than 4 bytes in size or is not
    /// correctly aligned.
    #[inline]
    pub fn as_u32(&self) -> Option<RacyU32<'a>> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < size_of::<u32>() || !self.ptr.as_ptr().cast::<u32>().is_aligned() {
            None
        } else {
            Some(RacyU32::from_ptr(self.ptr.as_ptr()))
        }
    }

    /// Convert the memory into a racy atomic u64 at the start of the slice.
    /// Returns None if the slice is smaller than 8 bytes in size or is not
    /// correctly aligned.
    #[inline]
    pub fn as_u64(&self) -> Option<RacyU64<'a>> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < size_of::<u64>() || !self.ptr.as_ptr().cast::<u64>().is_aligned() {
            None
        } else {
            Some(RacyU64::from_ptr(self.ptr.as_ptr()))
        }
    }

    /// Convert the memory into a racy atomic usize at the start of the slice.
    /// Returns None if the slice is smaller than `size_of::<usize>()` bytes in
    /// size or is not correctly aligned.
    #[inline]
    pub fn as_usize(&self) -> Option<RacyUsize<'a>> {
        // SAFETY: Slice should always be aligned to its own type.
        unsafe { assert_unchecked(self.ptr.as_ptr().cast::<T>().is_aligned()) };
        if self.byte_length() < size_of::<usize>()
            || !self.ptr.as_ptr().cast::<usize>().is_aligned()
        {
            None
        } else {
            Some(RacyUsize::from_ptr(self.ptr.as_ptr()))
        }
    }

    /// Copies all elements from `src` into `self` using a racy atomic memcpy.
    /// Note that the source slice uses the Rust memory model and this method
    /// abides by that: the source slice is only read from and no data races
    /// in the source memory are possible through the use of this function.
    ///
    /// The length of `src` must be the same as `self`.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    pub fn copy_from_slice(&self, src: &[T]) {
        if self.len() != src.len() {
            len_mismatch_fail();
        }
        let count = self.len();
        // SAFETY: slice pointers are always non-null.
        let src = unsafe { NonNull::new_unchecked(src.as_ptr().cast_mut()) };
        let dst: NonNull<T> = self.as_ptr().as_ptr().cast();
        // SAFETY: lengths are checked to match, and racy slice cannot overlap
        // with a Rust slice.
        unsafe { unordered_copy_nonoverlapping(src, dst, count) };
    }

    /// Copies all elements from `self` into `dst`, using a racy atomic memcpy.
    /// Note that the target slice uses the Rust memory model and this method
    /// abides by that: the target slice is held exclusively during the writing
    /// and thus no data races in the target memory are possible through the
    /// use of this function.
    ///
    /// The length of `dst` must be the same as `self`.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    pub fn copy_into_slice(&self, dst: &mut [T]) {
        if self.len() != dst.len() {
            len_mismatch_fail();
        }
        let count = self.len();
        let src: NonNull<T> = self.as_ptr().as_ptr().cast();
        // SAFETY: slice pointers are always non-null.
        let dst = unsafe { NonNull::new_unchecked(dst.as_ptr().cast_mut()) };
        // SAFETY: lengths are checked to match, and racy slice cannot overlap
        // with a Rust slice.
        unsafe { unordered_copy_nonoverlapping(src, dst, count) };
    }

    /// Copies all elements from `src` into `self`, using a racy memmove or
    /// memcpy as appropriate.
    ///
    /// The length of `src` must be the same as `self`.
    ///
    /// # Panics
    ///
    /// This function will panic if the two slices have different lengths.
    pub fn copy_from_racy_slice(&self, other: &Self) {
        if self.len() != other.len() {
            len_mismatch_fail();
        }
        let count = self.len();
        // SAFETY: slice is guaranteed to point to len valid elements.
        if unsafe {
            self.ptr.as_ptr() <= other.ptr.as_ptr()
                && other.ptr.as_ptr() < self.ptr.as_ptr().byte_add(self.byte_length())
                || other.ptr.as_ptr() <= self.ptr.as_ptr()
                    && self.ptr.as_ptr() < other.ptr.as_ptr().byte_add(other.byte_length())
        } {
            // Overlapping data.
            // SAFETY: Count checked to be valid for both.
            unsafe { unordered_copy(other.as_ptr(), self.as_ptr(), count) };
        } else {
            let dst: NonNull<T> = self.as_ptr().as_ptr().cast();
            let src: NonNull<T> = other.as_ptr().as_ptr().cast();
            // SAFETY: Count checked to be valid for both.
            unsafe { unordered_copy_nonoverlapping(src, dst, count) };
        }
    }
}

#[track_caller]
#[cold]
const fn len_mismatch_fail() -> ! {
    panic!("copy_from_slice: source slice length does not match destination slice length")
}

impl<'a> RacySlice<'a, u8> {
    /// Returns a racy element at the given position or `None` if out of
    /// bounds.
    pub fn get(&self, index: usize) -> Option<RacyU8<'a>> {
        self.slice_from(index).as_u8()
    }
}

impl<'a> RacySlice<'a, u16> {
    /// Returns a racy element at the given position or `None` if out of
    /// bounds.
    pub fn get(&self, index: usize) -> Option<RacyU16<'a>> {
        self.slice_from(index).as_u16()
    }
}

impl<'a> RacySlice<'a, u32> {
    /// Returns a racy element at the given position or `None` if out of
    /// bounds.
    pub fn get(&self, index: usize) -> Option<RacyU32<'a>> {
        self.slice_from(index).as_u32()
    }
}

impl<'a> RacySlice<'a, u64> {
    /// Returns a racy element at the given position or `None` if out of
    /// bounds.
    pub fn get(&self, index: usize) -> Option<RacyU64<'a>> {
        self.slice_from(index).as_u64()
    }
}

impl<'a> RacySlice<'a, usize> {
    /// Returns a racy element at the given position or `None` if out of
    /// bounds.
    pub fn get(&self, index: usize) -> Option<RacyUsize<'a>> {
        self.slice_from(index).as_usize()
    }
}

/// Opaque pointer to memory in the ECMAScript racy atomics memory model.
///
/// This is intended for unsafe usage only, where eg. the size of an EMCAScript
/// memory is stored separately from the pointer.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct RacyPtr<T: Sealed>(NonNull<()>, PhantomData<NonNull<UnsafeCell<T>>>);

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl<T: Sealed> Send for RacyPtr<T> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl<T: Sealed> Sync for RacyPtr<T> {}

impl<T: Sealed> RacyPtr<T> {
    /// Creates a new racy pointer that is dangling, but non-null and
    /// well-aligned.
    #[inline(always)]
    #[must_use]
    pub const fn dangling() -> RacyPtr<T> {
        Self::from_ptr(NonNull::<T>::dangling().cast())
    }

    const fn from_ptr(ptr: NonNull<()>) -> Self {
        Self(ptr, PhantomData)
    }

    /// Get racy atomic pointer as a non-null pointer.
    ///
    /// # Soundness
    ///
    /// While this provides a Rust-recognisable pointer, this pointer is
    /// invalid and cannot be used to read or write any data. The only
    /// meaningful operation on the pointer is to perform possible offsetting.
    pub const fn as_ptr(self) -> NonNull<()> {
        self.0
    }

    /// Casts to a pointer of another type.
    pub const fn cast<U: Sealed>(self) -> RacyPtr<U> {
        RacyPtr(self.0.cast(), PhantomData)
    }
}

/// An opaque pointer to a byte of memory implementing the ECMAScript atomic
/// memory model.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RacyU8<'a>(NonNull<()>, PhantomData<&'a UnsafeCell<u8>>);

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Send for RacyU8<'_> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Sync for RacyU8<'_> {}

impl RacyU8<'_> {
    fn from_ptr(ptr: NonNull<()>) -> Self {
        Self(ptr, PhantomData)
    }

    fn as_ptr(&self) -> NonNull<()> {
        self.0
    }

    /// Stores a value into the racy atomic integer if the current value is the
    /// same as the `current` value.
    ///
    /// The return value is a result indicating whether the new value was
    /// written and containing the previous value. On success this value is
    /// guaranteed to be equal to `current`.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn compare_exchange(&self, current: u8, new: u8) -> Result<u8, u8> {
        let old = atomic_cmp_xchg_8_seq_cst(self.as_ptr(), current, new);
        if old == current { Ok(old) } else { Err(old) }
    }

    /// Adds to the current value, returning the previous value.
    ///
    /// This operation wraps around on overflow.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_add(&self, val: u8) -> u8 {
        atomic_add_8_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_and(&self, val: u8) -> u8 {
        atomic_and_8_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_or(&self, val: u8) -> u8 {
        atomic_or_8_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_xor(&self, val: u8) -> u8 {
        atomic_xor_8_seq_cst(self.as_ptr(), val)
    }

    /// Loads a value from the atomic integer.
    ///
    /// `load` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn load(&self, order: Ordering) -> u8 {
        if order == Ordering::SeqCst {
            atomic_load_8_seq_cst(self.as_ptr())
        } else {
            atomic_load_8_unsynchronized(self.as_ptr())
        }
    }

    /// Stores a value into the atomic integer.
    ///
    /// `store` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn store(&self, val: u8, order: Ordering) {
        if order == Ordering::SeqCst {
            atomic_store_8_seq_cst(self.as_ptr(), val)
        } else {
            atomic_store_8_unsynchronized(self.as_ptr(), val)
        }
    }

    /// Stores a value into the atomic integer, returning the previous value.
    ///
    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn swap(&self, val: u8) -> u8 {
        atomic_exchange_8_seq_cst(self.as_ptr(), val)
    }
}

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RacyU16<'a>(NonNull<()>, PhantomData<&'a UnsafeCell<u16>>);

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Send for RacyU16<'_> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Sync for RacyU16<'_> {}

impl RacyU16<'_> {
    fn from_ptr(ptr: NonNull<()>) -> Self {
        Self(ptr, PhantomData)
    }

    fn as_ptr(&self) -> NonNull<()> {
        self.0
    }

    /// Stores a value into the racy atomic integer if the current value is the
    /// same as the `current` value.
    ///
    /// The return value is a result indicating whether the new value was
    /// written and containing the previous value. On success this value is
    /// guaranteed to be equal to `current`.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn compare_exchange(&self, current: u16, new: u16) -> Result<u16, u16> {
        let old = atomic_cmp_xchg_16_seq_cst(self.as_ptr(), current, new);
        if old == current { Ok(old) } else { Err(old) }
    }

    /// Adds to the current value, returning the previous value.
    ///
    /// This operation wraps around on overflow.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_add(&self, val: u16) -> u16 {
        atomic_add_16_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_and(&self, val: u16) -> u16 {
        atomic_and_16_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_or(&self, val: u16) -> u16 {
        atomic_or_16_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_xor(&self, val: u16) -> u16 {
        atomic_xor_16_seq_cst(self.as_ptr(), val)
    }

    /// Loads a value from the atomic integer.
    ///
    /// `load` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn load(&self, order: Ordering) -> u16 {
        if order == Ordering::SeqCst {
            atomic_load_16_seq_cst(self.as_ptr())
        } else {
            atomic_load_16_unsynchronized(self.as_ptr())
        }
    }

    /// Stores a value into the atomic integer.
    ///
    /// `store` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn store(&self, val: u16, order: Ordering) {
        if order == Ordering::SeqCst {
            atomic_store_16_seq_cst(self.as_ptr(), val)
        } else {
            atomic_store_16_unsynchronized(self.as_ptr(), val)
        }
    }

    /// Stores a value into the atomic integer, returning the previous value.
    ///
    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn swap(&self, val: u16) -> u16 {
        atomic_exchange_16_seq_cst(self.as_ptr(), val)
    }
}

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RacyU32<'a>(NonNull<()>, PhantomData<&'a UnsafeCell<u32>>);

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Send for RacyU32<'_> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Sync for RacyU32<'_> {}

impl RacyU32<'_> {
    fn from_ptr(ptr: NonNull<()>) -> Self {
        Self(ptr, PhantomData)
    }

    fn as_ptr(&self) -> NonNull<()> {
        self.0
    }

    /// Stores a value into the racy atomic integer if the current value is the
    /// same as the `current` value.
    ///
    /// The return value is a result indicating whether the new value was
    /// written and containing the previous value. On success this value is
    /// guaranteed to be equal to `current`.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn compare_exchange(&self, current: u32, new: u32) -> Result<u32, u32> {
        let old = atomic_cmp_xchg_32_seq_cst(self.as_ptr(), current, new);
        if old == current { Ok(old) } else { Err(old) }
    }

    /// Adds to the current value, returning the previous value.
    ///
    /// This operation wraps around on overflow.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_add(&self, val: u32) -> u32 {
        atomic_add_32_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_and(&self, val: u32) -> u32 {
        atomic_and_32_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_or(&self, val: u32) -> u32 {
        atomic_or_32_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn fetch_xor(&self, val: u32) -> u32 {
        atomic_xor_32_seq_cst(self.as_ptr(), val)
    }

    /// Loads a value from the atomic integer.
    ///
    /// `load` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn load(&self, order: Ordering) -> u32 {
        if order == Ordering::SeqCst {
            atomic_load_32_seq_cst(self.as_ptr())
        } else {
            atomic_load_32_unsynchronized(self.as_ptr())
        }
    }

    /// Stores a value into the atomic integer.
    ///
    /// `store` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn store(&self, val: u32, order: Ordering) {
        if order == Ordering::SeqCst {
            atomic_store_32_seq_cst(self.as_ptr(), val)
        } else {
            atomic_store_32_unsynchronized(self.as_ptr(), val)
        }
    }

    /// Stores a value into the atomic integer, returning the previous value.
    ///
    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn swap(&self, val: u32) -> u32 {
        atomic_exchange_32_seq_cst(self.as_ptr(), val)
    }
}

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RacyU64<'a>(NonNull<()>, PhantomData<&'a UnsafeCell<u64>>);

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Send for RacyU64<'_> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Sync for RacyU64<'_> {}

impl RacyU64<'_> {
    fn from_ptr(ptr: NonNull<()>) -> Self {
        Self(ptr, PhantomData)
    }

    fn as_ptr(&self) -> NonNull<()> {
        self.0
    }

    /// Stores a value into the racy atomic integer if the current value is the
    /// same as the `current` value.
    ///
    /// The return value is a result indicating whether the new value was
    /// written and containing the previous value. On success this value is
    /// guaranteed to be equal to `current`.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn compare_exchange(&self, current: u64, new: u64) -> Result<u64, u64> {
        let old = atomic_cmp_xchg_64_seq_cst(self.as_ptr(), current, new);
        if old == current { Ok(old) } else { Err(old) }
    }

    /// Adds to the current value, returning the previous value.
    ///
    /// This operation wraps around on overflow.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_add(&self, val: u64) -> u64 {
        atomic_add_64_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_and(&self, val: u64) -> u64 {
        atomic_and_64_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_or(&self, val: u64) -> u64 {
        atomic_or_64_seq_cst(self.as_ptr(), 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_xor(&self, val: u64) -> u64 {
        atomic_xor_64_seq_cst(self.as_ptr(), val)
    }

    /// Loads a value from the atomic integer.
    ///
    /// `load` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn load(&self, order: Ordering) -> u64 {
        if order == Ordering::SeqCst {
            atomic_load_64_seq_cst(self.as_ptr())
        } else {
            atomic_load_64_unsynchronized(self.as_ptr())
        }
    }

    /// Stores a value into the atomic integer.
    ///
    /// `store` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn store(&self, val: u64, order: Ordering) {
        if order == Ordering::SeqCst {
            atomic_store_64_seq_cst(self.as_ptr(), val)
        } else {
            atomic_store_64_unsynchronized(self.as_ptr(), val)
        }
    }

    /// Stores a value into the atomic integer, returning the previous value.
    ///
    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn swap(&self, val: u64) -> u64 {
        atomic_exchange_64_seq_cst(self.as_ptr(), val)
    }
}

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RacyUsize<'a>(NonNull<()>, PhantomData<&'a UnsafeCell<usize>>);

// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Send for RacyUsize<'_> {}
// SAFETY: Racy atomics are safe to access from multiple threads.
unsafe impl Sync for RacyUsize<'_> {}

impl RacyUsize<'_> {
    fn from_ptr(ptr: NonNull<()>) -> Self {
        Self(ptr, PhantomData)
    }

    fn as_ptr(&self) -> NonNull<()> {
        self.0
    }

    /// Stores a value into the racy atomic integer if the current value is the
    /// same as the `current` value.
    ///
    /// The return value is a result indicating whether the new value was
    /// written and containing the previous value. On success this value is
    /// guaranteed to be equal to `current`.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(
        target_arch = "x86",
        target_arch = "x86_64",
        target_arch = "aarch64",
        target_arch = "arm"
    ))]
    pub fn compare_exchange(&self, current: usize, new: usize) -> Result<usize, usize> {
        #[cfg(target_pointer_width = "16")]
        {
            let old =
                atomic_cmp_xchg_16_seq_cst(self.as_ptr(), current as u16, new as u16) as usize;
            if old == current { Ok(old) } else { Err(old) }
        }
        #[cfg(target_pointer_width = "32")]
        {
            let old =
                atomic_cmp_xchg_16_seq_cst(self.as_ptr(), current as u32, new as u32) as usize;
            if old == current { Ok(old) } else { Err(old) }
        }
        #[cfg(target_pointer_width = "64")]
        {
            let old =
                atomic_cmp_xchg_64_seq_cst(self.as_ptr(), current as u64, new as u64) as usize;
            if old == current { Ok(old) } else { Err(old) }
        }
    }

    /// Adds to the current value, returning the previous value.
    ///
    /// This operation wraps around on overflow.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_add(&self, val: usize) -> usize {
        #[cfg(target_pointer_width = "16")]
        {
            atomic_add_16_seq_cst(self.as_ptr(), val as u16) as usize
        }
        #[cfg(target_pointer_width = "32")]
        {
            atomic_add_32_seq_cst(self.as_ptr(), val as u32) as usize
        }
        #[cfg(target_pointer_width = "64")]
        {
            atomic_add_64_seq_cst(self.as_ptr(), val as u64) as usize
        }
    }

    /// 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_and(&self, val: usize) -> usize {
        #[cfg(target_pointer_width = "16")]
        {
            atomic_and_16_seq_cst(self.as_ptr(), val as u16) as usize
        }
        #[cfg(target_pointer_width = "32")]
        {
            atomic_and_32_seq_cst(self.as_ptr(), val as u32) as usize
        }
        #[cfg(target_pointer_width = "64")]
        {
            atomic_and_64_seq_cst(self.as_ptr(), val as u64) as usize
        }
    }

    /// 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_or(&self, val: usize) -> usize {
        #[cfg(target_pointer_width = "16")]
        {
            atomic_or_16_seq_cst(self.as_ptr(), val as u16) as usize
        }
        #[cfg(target_pointer_width = "32")]
        {
            atomic_or_32_seq_cst(self.as_ptr(), val as u32) as usize
        }
        #[cfg(target_pointer_width = "64")]
        {
            atomic_or_64_seq_cst(self.as_ptr(), val as u64) as usize
        }
    }

    /// 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.
    ///
    /// Returns the previous value.
    ///
    /// The [`Ordering`] of the operation is always [`SeqCst`].
    ///
    /// [`Ordering`]: crate::Ordering
    /// [`SeqCst`]: crate::Ordering::SeqCst
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn fetch_xor(&self, val: usize) -> usize {
        #[cfg(target_pointer_width = "16")]
        {
            atomic_xor_16_seq_cst(self.as_ptr(), val as u16) as usize
        }
        #[cfg(target_pointer_width = "32")]
        {
            atomic_xor_32_seq_cst(self.as_ptr(), val as u32) as usize
        }
        #[cfg(target_pointer_width = "64")]
        {
            atomic_xor_64_seq_cst(self.as_ptr(), val as u64) as usize
        }
    }

    /// Loads a value from the atomic integer.
    ///
    /// `load` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn load(&self, order: Ordering) -> usize {
        #[cfg(target_pointer_width = "16")]
        {
            if order == Ordering::SeqCst {
                atomic_load_16_seq_cst(self.as_ptr()) as usize
            } else {
                atomic_load_16_unsynchronized(self.as_ptr()) as usize
            }
        }
        #[cfg(target_pointer_width = "32")]
        {
            if order == Ordering::SeqCst {
                atomic_load_32_seq_cst(self.as_ptr()) as usize
            } else {
                atomic_load_32_unsynchronized(self.as_ptr()) as usize
            }
        }
        #[cfg(target_pointer_width = "64")]
        {
            if order == Ordering::SeqCst {
                atomic_load_64_seq_cst(self.as_ptr()) as usize
            } else {
                atomic_load_64_unsynchronized(self.as_ptr()) as usize
            }
        }
    }

    /// Stores a value into the atomic integer.
    ///
    /// `store` takes an [`Ordering`] argument which describes the memory
    /// ordering of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn store(&self, val: usize, order: Ordering) {
        #[cfg(target_pointer_width = "16")]
        {
            if order == Ordering::SeqCst {
                atomic_store_16_seq_cst(self.as_ptr(), val as u16)
            } else {
                atomic_store_16_unsynchronized(self.as_ptr(), val as u16)
            }
        }
        #[cfg(target_pointer_width = "32")]
        {
            if order == Ordering::SeqCst {
                atomic_store_32_seq_cst(self.as_ptr(), val as u32)
            } else {
                atomic_store_32_unsynchronized(self.as_ptr(), val as u32)
            }
        }
        #[cfg(target_pointer_width = "64")]
        {
            if order == Ordering::SeqCst {
                atomic_store_64_seq_cst(self.as_ptr(), val as u64)
            } else {
                atomic_store_64_unsynchronized(self.as_ptr(), val as u64)
            }
        }
    }

    /// Stores a value into the atomic integer, returning the previous value.
    ///
    /// `swap` takes an [`Ordering`] argument which describes the memory ordering
    /// of this operation. All ordering modes are possible.
    #[inline]
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))]
    pub fn swap(&self, val: usize) -> usize {
        #[cfg(target_pointer_width = "16")]
        {
            atomic_exchange_16_seq_cst(self.as_ptr(), val as u16) as usize
        }
        #[cfg(target_pointer_width = "32")]
        {
            atomic_exchange_32_seq_cst(self.as_ptr(), val as u32) as usize
        }
        #[cfg(target_pointer_width = "64")]
        {
            atomic_exchange_64_seq_cst(self.as_ptr(), val as u64) as usize
        }
    }
}

/// Copies `count` elements from `src` to `dst`. The source and destination
/// must *not* overlap.
///
/// For regions of memory which might overlap, use [`unordered_copy`] instead.
///
/// `unordered_copy_nonoverlapping` is semantically equivalent to C's
/// [`memcpy`], but with the source and destination arguments swapped, and with
/// data races allowed.
///
/// [`memcpy`]: https://en.cppreference.com/w/c/string/byte/memcpy
///
/// # Safety
///
/// Behavior is undefined if any of the following conditions are violated:
///
/// * `src` must be [valid] for reads of `count` elements.
///
/// * `dst` must be [valid] for writes of `count` elements.
///
/// * Both `src` and `dst` must be properly aligned.
///
/// * The region of memory beginning at `src` with a size of `count` elements
///   must *not* overlap with the region of memory beginning at `dst` with the
///   same size.
///
/// [valid]: https://doc.rust-lang.org/stable/core/ptr/#safety
#[inline]
unsafe fn unordered_copy_nonoverlapping<T: Sealed>(src: NonNull<T>, dst: NonNull<T>, count: usize) {
    let count = count * size_of::<T>();
    unsafe { unordered_memcpy_down_unsynchronized(src.cast(), dst.cast(), count) };
}

/// Copies `count` elements from `src` to `dst`. The source and destination may
/// overlap.
///
/// If the source and destination will *never* overlap,
/// [`unordered_copy_nonoverlapping`] can be used instead.
///
/// `unordered_copy` is semantically equivalent to C's [`memmove`], but with
/// the source and destination arguments swapped, and with data races allowed.
/// Copying takes place as if the elements were copied from `src` to a
/// temporary array and then copied from the array to `dst`.
///
/// [`memmove`]: https://en.cppreference.com/w/c/string/byte/memmove
///
/// # Safety
///
/// Behavior is undefined if any of the following conditions are violated:
///
/// * `src` must be [valid] for reads of `count` elements, OR it must be an
///   opaque racy handle into a racy slice of `count` elements.
///
/// * `dst` must be [valid] for writes of `count` elements, and must remain
///   valid even when `src` is read for `count` elements (this means if the
///   memory ranges overlap, the `dst` pointer must not be invalidated by
///   `src` reads), OR it must be an opaque racy handle into a racy slice of
///   `count` elements.
///
/// [valid]: https://doc.rust-lang.org/stable/core/ptr/#safety
#[inline]
unsafe fn unordered_copy<T: Sealed>(src: RacyPtr<T>, dst: RacyPtr<T>, count: usize) {
    let count = count * size_of::<T>();
    if dst.as_ptr() <= src.as_ptr() {
        unsafe { unordered_memcpy_down_unsynchronized(src.as_ptr(), dst.as_ptr(), count) };
    } else {
        unsafe { unordered_memcpy_up_unsynchronized(src.as_ptr(), dst.as_ptr(), count) };
    }
}