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
|
#[cfg(feature = "std")]
use std::sync::Barrier;
use std::{
num::NonZeroUsize,
sync::atomic::{AtomicUsize, Ordering::SeqCst},
thread::scope,
};
use once_cell::race::{OnceBool, OnceNonZeroUsize};
#[test]
fn once_non_zero_usize_smoke_test() {
let cnt = AtomicUsize::new(0);
let cell = OnceNonZeroUsize::new();
let val = NonZeroUsize::new(92).unwrap();
scope(|s| {
s.spawn(|| {
assert_eq!(
cell.get_or_init(|| {
cnt.fetch_add(1, SeqCst);
val
}),
val
);
assert_eq!(cnt.load(SeqCst), 1);
assert_eq!(
cell.get_or_init(|| {
cnt.fetch_add(1, SeqCst);
val
}),
val
);
assert_eq!(cnt.load(SeqCst), 1);
});
});
assert_eq!(cell.get(), Some(val));
assert_eq!(cnt.load(SeqCst), 1);
}
#[test]
fn once_non_zero_usize_set() {
let val1 = NonZeroUsize::new(92).unwrap();
let val2 = NonZeroUsize::new(62).unwrap();
let cell = OnceNonZeroUsize::new();
assert!(cell.set(val1).is_ok());
assert_eq!(cell.get(), Some(val1));
assert!(cell.set(val2).is_err());
assert_eq!(cell.get(), Some(val1));
}
#[cfg(feature = "std")]
#[test]
fn once_non_zero_usize_first_wins() {
let val1 = NonZeroUsize::new(92).unwrap();
let val2 = NonZeroUsize::new(62).unwrap();
let cell = OnceNonZeroUsize::new();
let b1 = Barrier::new(2);
let b2 = Barrier::new(2);
let b3 = Barrier::new(2);
scope(|s| {
s.spawn(|| {
let r1 = cell.get_or_init(|| {
b1.wait();
b2.wait();
val1
});
assert_eq!(r1, val1);
b3.wait();
});
b1.wait();
s.spawn(|| {
let r2 = cell.get_or_init(|| {
b2.wait();
b3.wait();
val2
});
assert_eq!(r2, val1);
});
});
assert_eq!(cell.get(), Some(val1));
}
#[test]
fn once_bool_smoke_test() {
let cnt = AtomicUsize::new(0);
let cell = OnceBool::new();
scope(|s| {
s.spawn(|| {
assert_eq!(
cell.get_or_init(|| {
cnt.fetch_add(1, SeqCst);
false
}),
false
);
assert_eq!(cnt.load(SeqCst), 1);
assert_eq!(
cell.get_or_init(|| {
cnt.fetch_add(1, SeqCst);
false
}),
false
);
assert_eq!(cnt.load(SeqCst), 1);
});
});
assert_eq!(cell.get(), Some(false));
assert_eq!(cnt.load(SeqCst), 1);
}
#[test]
fn once_bool_set() {
let cell = OnceBool::new();
assert!(cell.set(false).is_ok());
assert_eq!(cell.get(), Some(false));
assert!(cell.set(true).is_err());
assert_eq!(cell.get(), Some(false));
}
|