1 | use std::{ |
2 | sync::atomic::{AtomicUsize, Ordering::SeqCst}, |
3 | thread::scope, |
4 | }; |
5 | |
6 | #[cfg (feature = "std" )] |
7 | use std::sync::Barrier; |
8 | |
9 | #[cfg (not(feature = "std" ))] |
10 | use core::cell::Cell; |
11 | |
12 | use once_cell::sync::{Lazy, OnceCell}; |
13 | |
14 | #[test] |
15 | fn once_cell() { |
16 | let c = OnceCell::new(); |
17 | assert!(c.get().is_none()); |
18 | scope(|s| { |
19 | s.spawn(|| { |
20 | c.get_or_init(|| 92); |
21 | assert_eq!(c.get(), Some(&92)); |
22 | }); |
23 | }); |
24 | c.get_or_init(|| panic!("Kabom!" )); |
25 | assert_eq!(c.get(), Some(&92)); |
26 | } |
27 | |
28 | #[test] |
29 | fn once_cell_with_value() { |
30 | static CELL: OnceCell<i32> = OnceCell::with_value(12); |
31 | assert_eq!(CELL.get(), Some(&12)); |
32 | } |
33 | |
34 | #[test] |
35 | fn once_cell_get_mut() { |
36 | let mut c = OnceCell::new(); |
37 | assert!(c.get_mut().is_none()); |
38 | c.set(90).unwrap(); |
39 | *c.get_mut().unwrap() += 2; |
40 | assert_eq!(c.get_mut(), Some(&mut 92)); |
41 | } |
42 | |
43 | #[test] |
44 | fn once_cell_get_unchecked() { |
45 | let c = OnceCell::new(); |
46 | c.set(92).unwrap(); |
47 | unsafe { |
48 | assert_eq!(c.get_unchecked(), &92); |
49 | } |
50 | } |
51 | |
52 | #[test] |
53 | fn once_cell_drop() { |
54 | static DROP_CNT: AtomicUsize = AtomicUsize::new(0); |
55 | struct Dropper; |
56 | impl Drop for Dropper { |
57 | fn drop(&mut self) { |
58 | DROP_CNT.fetch_add(1, SeqCst); |
59 | } |
60 | } |
61 | |
62 | let x = OnceCell::new(); |
63 | scope(|s| { |
64 | s.spawn(|| { |
65 | x.get_or_init(|| Dropper); |
66 | assert_eq!(DROP_CNT.load(SeqCst), 0); |
67 | drop(x); |
68 | }); |
69 | }); |
70 | assert_eq!(DROP_CNT.load(SeqCst), 1); |
71 | } |
72 | |
73 | #[test] |
74 | fn once_cell_drop_empty() { |
75 | let x = OnceCell::<String>::new(); |
76 | drop(x); |
77 | } |
78 | |
79 | #[test] |
80 | fn clone() { |
81 | let s = OnceCell::new(); |
82 | let c = s.clone(); |
83 | assert!(c.get().is_none()); |
84 | |
85 | s.set("hello" .to_string()).unwrap(); |
86 | let c = s.clone(); |
87 | assert_eq!(c.get().map(String::as_str), Some("hello" )); |
88 | } |
89 | |
90 | #[test] |
91 | fn get_or_try_init() { |
92 | let cell: OnceCell<String> = OnceCell::new(); |
93 | assert!(cell.get().is_none()); |
94 | |
95 | let res = std::panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() })); |
96 | assert!(res.is_err()); |
97 | assert!(cell.get().is_none()); |
98 | |
99 | assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); |
100 | |
101 | assert_eq!(cell.get_or_try_init(|| Ok::<_, ()>("hello" .to_string())), Ok(&"hello" .to_string())); |
102 | assert_eq!(cell.get(), Some(&"hello" .to_string())); |
103 | } |
104 | |
105 | #[cfg (feature = "std" )] |
106 | #[test] |
107 | fn wait() { |
108 | let cell: OnceCell<String> = OnceCell::new(); |
109 | scope(|s| { |
110 | s.spawn(|| cell.set("hello" .to_string())); |
111 | let greeting = cell.wait(); |
112 | assert_eq!(greeting, "hello" ) |
113 | }); |
114 | } |
115 | |
116 | #[cfg (feature = "std" )] |
117 | #[test] |
118 | fn get_or_init_stress() { |
119 | let n_threads = if cfg!(miri) { 30 } else { 1_000 }; |
120 | let n_cells = if cfg!(miri) { 30 } else { 1_000 }; |
121 | let cells: Vec<_> = std::iter::repeat_with(|| (Barrier::new(n_threads), OnceCell::new())) |
122 | .take(n_cells) |
123 | .collect(); |
124 | scope(|s| { |
125 | for t in 0..n_threads { |
126 | let cells = &cells; |
127 | s.spawn(move || { |
128 | for (i, (b, s)) in cells.iter().enumerate() { |
129 | b.wait(); |
130 | let j = if t % 2 == 0 { s.wait() } else { s.get_or_init(|| i) }; |
131 | assert_eq!(*j, i); |
132 | } |
133 | }); |
134 | } |
135 | }); |
136 | } |
137 | |
138 | #[test] |
139 | fn from_impl() { |
140 | assert_eq!(OnceCell::from("value" ).get(), Some(&"value" )); |
141 | assert_ne!(OnceCell::from("foo" ).get(), Some(&"bar" )); |
142 | } |
143 | |
144 | #[test] |
145 | fn partialeq_impl() { |
146 | assert!(OnceCell::from("value" ) == OnceCell::from("value" )); |
147 | assert!(OnceCell::from("foo" ) != OnceCell::from("bar" )); |
148 | |
149 | assert!(OnceCell::<String>::new() == OnceCell::new()); |
150 | assert!(OnceCell::<String>::new() != OnceCell::from("value" .to_owned())); |
151 | } |
152 | |
153 | #[test] |
154 | fn into_inner() { |
155 | let cell: OnceCell<String> = OnceCell::new(); |
156 | assert_eq!(cell.into_inner(), None); |
157 | let cell = OnceCell::new(); |
158 | cell.set("hello" .to_string()).unwrap(); |
159 | assert_eq!(cell.into_inner(), Some("hello" .to_string())); |
160 | } |
161 | |
162 | #[test] |
163 | fn debug_impl() { |
164 | let cell = OnceCell::new(); |
165 | assert_eq!(format!("{:#?}" , cell), "OnceCell(Uninit)" ); |
166 | cell.set(vec!["hello" , "world" ]).unwrap(); |
167 | assert_eq!( |
168 | format!("{:#?}" , cell), |
169 | r#"OnceCell( |
170 | [ |
171 | "hello", |
172 | "world", |
173 | ], |
174 | )"# |
175 | ); |
176 | } |
177 | |
178 | #[test] |
179 | #[cfg_attr (miri, ignore)] // miri doesn't support processes |
180 | #[cfg (feature = "std" )] |
181 | fn reentrant_init() { |
182 | let examples_dir = { |
183 | let mut exe = std::env::current_exe().unwrap(); |
184 | exe.pop(); |
185 | exe.pop(); |
186 | exe.push("examples" ); |
187 | exe |
188 | }; |
189 | let bin = examples_dir |
190 | .join("reentrant_init_deadlocks" ) |
191 | .with_extension(std::env::consts::EXE_EXTENSION); |
192 | let mut guard = Guard { child: std::process::Command::new(bin).spawn().unwrap() }; |
193 | std::thread::sleep(std::time::Duration::from_secs(2)); |
194 | let status = guard.child.try_wait().unwrap(); |
195 | assert!(status.is_none()); |
196 | |
197 | struct Guard { |
198 | child: std::process::Child, |
199 | } |
200 | |
201 | impl Drop for Guard { |
202 | fn drop(&mut self) { |
203 | let _ = self.child.kill(); |
204 | } |
205 | } |
206 | } |
207 | |
208 | #[cfg (not(feature = "std" ))] |
209 | #[test] |
210 | #[should_panic (expected = "reentrant init" )] |
211 | fn reentrant_init() { |
212 | let x: OnceCell<Box<i32>> = OnceCell::new(); |
213 | let dangling_ref: Cell<Option<&i32>> = Cell::new(None); |
214 | x.get_or_init(|| { |
215 | let r = x.get_or_init(|| Box::new(92)); |
216 | dangling_ref.set(Some(r)); |
217 | Box::new(62) |
218 | }); |
219 | eprintln!("use after free: {:?}" , dangling_ref.get().unwrap()); |
220 | } |
221 | |
222 | #[test] |
223 | fn eval_once_macro() { |
224 | macro_rules! eval_once { |
225 | (|| -> $ty:ty { |
226 | $($body:tt)* |
227 | }) => {{ |
228 | static ONCE_CELL: OnceCell<$ty> = OnceCell::new(); |
229 | fn init() -> $ty { |
230 | $($body)* |
231 | } |
232 | ONCE_CELL.get_or_init(init) |
233 | }}; |
234 | } |
235 | |
236 | let fib: &'static Vec<i32> = eval_once! { |
237 | || -> Vec<i32> { |
238 | let mut res = vec![1, 1]; |
239 | for i in 0..10 { |
240 | let next = res[i] + res[i + 1]; |
241 | res.push(next); |
242 | } |
243 | res |
244 | } |
245 | }; |
246 | assert_eq!(fib[5], 8) |
247 | } |
248 | |
249 | #[test] |
250 | fn once_cell_does_not_leak_partially_constructed_boxes() { |
251 | let n_tries = if cfg!(miri) { 10 } else { 100 }; |
252 | let n_readers = 10; |
253 | let n_writers = 3; |
254 | const MSG: &str = "Hello, World" ; |
255 | |
256 | for _ in 0..n_tries { |
257 | let cell: OnceCell<String> = OnceCell::new(); |
258 | scope(|scope| { |
259 | for _ in 0..n_readers { |
260 | scope.spawn(|| loop { |
261 | if let Some(msg) = cell.get() { |
262 | assert_eq!(msg, MSG); |
263 | break; |
264 | } |
265 | }); |
266 | } |
267 | for _ in 0..n_writers { |
268 | let _ = scope.spawn(|| cell.set(MSG.to_owned())); |
269 | } |
270 | }); |
271 | } |
272 | } |
273 | |
274 | #[cfg (feature = "std" )] |
275 | #[test] |
276 | fn get_does_not_block() { |
277 | let cell = OnceCell::new(); |
278 | let barrier = Barrier::new(2); |
279 | scope(|scope| { |
280 | scope.spawn(|| { |
281 | cell.get_or_init(|| { |
282 | barrier.wait(); |
283 | barrier.wait(); |
284 | "hello" .to_string() |
285 | }); |
286 | }); |
287 | barrier.wait(); |
288 | assert_eq!(cell.get(), None); |
289 | barrier.wait(); |
290 | }); |
291 | assert_eq!(cell.get(), Some(&"hello" .to_string())); |
292 | } |
293 | |
294 | #[test] |
295 | // https://github.com/rust-lang/rust/issues/34761#issuecomment-256320669 |
296 | fn arrrrrrrrrrrrrrrrrrrrrr() { |
297 | let cell = OnceCell::new(); |
298 | { |
299 | let s = String::new(); |
300 | cell.set(&s).unwrap(); |
301 | } |
302 | } |
303 | |
304 | #[test] |
305 | fn once_cell_is_sync_send() { |
306 | fn assert_traits<T: Send + Sync>() {} |
307 | assert_traits::<OnceCell<String>>(); |
308 | assert_traits::<Lazy<String>>(); |
309 | } |
310 | |