1 //@compile-flags: -Zmiri-ignore-leaks
2
3 // Tests operations not performable through C++'s atomic API
4 // but doable in safe (at least sound) Rust.
5
6 #![feature(atomic_from_mut)]
7
8 use std::sync::atomic::Ordering::*;
9 use std::sync::atomic::{AtomicU16, AtomicU32};
10 use std::thread::spawn;
11
static_atomic_mut(val: u32) -> &'static mut AtomicU3212 fn static_atomic_mut(val: u32) -> &'static mut AtomicU32 {
13 let ret = Box::leak(Box::new(AtomicU32::new(val)));
14 ret
15 }
16
split_u32(dword: &mut u32) -> &mut [u16; 2]17 fn split_u32(dword: &mut u32) -> &mut [u16; 2] {
18 unsafe { std::mem::transmute::<&mut u32, &mut [u16; 2]>(dword) }
19 }
20
mem_replace()21 fn mem_replace() {
22 let mut x = AtomicU32::new(0);
23
24 let old_x = std::mem::replace(&mut x, AtomicU32::new(42));
25
26 assert_eq!(x.load(Relaxed), 42);
27 assert_eq!(old_x.load(Relaxed), 0);
28 }
29
assign_to_mut()30 fn assign_to_mut() {
31 let x = static_atomic_mut(0);
32 x.store(1, Relaxed);
33
34 *x = AtomicU32::new(2);
35
36 assert_eq!(x.load(Relaxed), 2);
37 }
38
get_mut_write()39 fn get_mut_write() {
40 let x = static_atomic_mut(0);
41 x.store(1, Relaxed);
42 {
43 let x_mut = x.get_mut();
44 *x_mut = 2;
45 }
46
47 let j1 = spawn(move || x.load(Relaxed));
48
49 let r1 = j1.join().unwrap();
50 assert_eq!(r1, 2);
51 }
52
53 // This is technically doable in C++ with atomic_ref
54 // but little literature exists atm on its involvement
55 // in mixed size/atomicity accesses
from_mut_split()56 fn from_mut_split() {
57 let mut x: u32 = 0;
58
59 {
60 let x_atomic = AtomicU32::from_mut(&mut x);
61 x_atomic.store(u32::from_be(0xabbafafa), Relaxed);
62 }
63
64 // Split the `AtomicU32` into two `AtomicU16`.
65 // Crucially, there is no non-atomic access to `x`! All accesses are atomic, but of different size.
66 let (x_hi, x_lo) = split_u32(&mut x).split_at_mut(1);
67
68 let x_hi_atomic = AtomicU16::from_mut(&mut x_hi[0]);
69 let x_lo_atomic = AtomicU16::from_mut(&mut x_lo[0]);
70
71 assert_eq!(x_hi_atomic.load(Relaxed), u16::from_be(0xabba));
72 assert_eq!(x_lo_atomic.load(Relaxed), u16::from_be(0xfafa));
73 }
74
main()75 pub fn main() {
76 get_mut_write();
77 from_mut_split();
78 assign_to_mut();
79 mem_replace();
80 }
81