3 lazy::{Lazy, OnceCell},
4 sync::atomic::{AtomicUsize, Ordering::SeqCst},
9 let c = OnceCell::new();
10 assert!(c.get().is_none());
12 assert_eq!(c.get(), Some(&92));
14 c.get_or_init(|| panic!("Kabom!"));
15 assert_eq!(c.get(), Some(&92));
19 fn once_cell_get_mut() {
20 let mut c = OnceCell::new();
21 assert!(c.get_mut().is_none());
23 *c.get_mut().unwrap() += 2;
24 assert_eq!(c.get_mut(), Some(&mut 92));
29 static DROP_CNT: AtomicUsize = AtomicUsize::new(0);
31 impl Drop for Dropper {
33 DROP_CNT.fetch_add(1, SeqCst);
37 let x = OnceCell::new();
38 x.get_or_init(|| Dropper);
39 assert_eq!(DROP_CNT.load(SeqCst), 0);
41 assert_eq!(DROP_CNT.load(SeqCst), 1);
45 fn unsync_once_cell_drop_empty() {
46 let x = OnceCell::<&'static str>::new();
51 const fn once_cell_const() {
52 let _once_cell: OnceCell<u32> = OnceCell::new();
53 let _once_cell: OnceCell<u32> = OnceCell::from(32);
58 let s = OnceCell::new();
60 assert!(c.get().is_none());
62 s.set("hello").unwrap();
64 assert_eq!(c.get().map(|c| *c), Some("hello"));
69 assert_eq!(OnceCell::from("value").get(), Some(&"value"));
70 assert_ne!(OnceCell::from("foo").get(), Some(&"bar"));
75 assert!(OnceCell::from("value") == OnceCell::from("value"));
76 assert!(OnceCell::from("foo") != OnceCell::from("bar"));
78 assert!(OnceCell::<&'static str>::new() == OnceCell::new());
79 assert!(OnceCell::<&'static str>::new() != OnceCell::from("value"));
84 let cell: OnceCell<&'static str> = OnceCell::new();
85 assert_eq!(cell.into_inner(), None);
86 let cell = OnceCell::new();
87 cell.set("hello").unwrap();
88 assert_eq!(cell.into_inner(), Some("hello"));
93 let called = Cell::new(0);
94 let x = Lazy::new(|| {
95 called.set(called.get() + 1);
99 assert_eq!(called.get(), 0);
103 assert_eq!(called.get(), 1);
107 assert_eq!(called.get(), 1);
111 fn aliasing_in_get() {
112 let x = OnceCell::new();
114 let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option<T>` --+
115 let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option<T>` |
116 println!("{at_x}"); // <------- up until here ---------------------------+
120 #[should_panic(expected = "reentrant init")]
121 fn reentrant_init() {
122 let x: OnceCell<Box<i32>> = OnceCell::new();
123 let dangling_ref: Cell<Option<&i32>> = Cell::new(None);
125 let r = x.get_or_init(|| Box::new(92));
126 dangling_ref.set(Some(r));
129 eprintln!("use after free: {:?}", dangling_ref.get().unwrap());
134 let cell = OnceCell::new();
136 let s = String::new();
137 cell.set(&s).unwrap();