2 cell::{Cell, LazyCell, OnceCell},
3 sync::atomic::{AtomicUsize, Ordering::SeqCst},
8 let c = OnceCell::new();
9 assert!(c.get().is_none());
11 assert_eq!(c.get(), Some(&92));
13 c.get_or_init(|| panic!("Kabom!"));
14 assert_eq!(c.get(), Some(&92));
18 fn once_cell_get_mut() {
19 let mut c = OnceCell::new();
20 assert!(c.get_mut().is_none());
22 *c.get_mut().unwrap() += 2;
23 assert_eq!(c.get_mut(), Some(&mut 92));
28 static DROP_CNT: AtomicUsize = AtomicUsize::new(0);
30 impl Drop for Dropper {
32 DROP_CNT.fetch_add(1, SeqCst);
36 let x = OnceCell::new();
37 x.get_or_init(|| Dropper);
38 assert_eq!(DROP_CNT.load(SeqCst), 0);
40 assert_eq!(DROP_CNT.load(SeqCst), 1);
44 fn unsync_once_cell_drop_empty() {
45 let x = OnceCell::<&'static str>::new();
50 const fn once_cell_const() {
51 let _once_cell: OnceCell<u32> = OnceCell::new();
52 let _once_cell: OnceCell<u32> = OnceCell::from(32);
57 let s = OnceCell::new();
59 assert!(c.get().is_none());
61 s.set("hello").unwrap();
63 assert_eq!(c.get().map(|c| *c), Some("hello"));
68 assert_eq!(OnceCell::from("value").get(), Some(&"value"));
69 assert_ne!(OnceCell::from("foo").get(), Some(&"bar"));
74 assert!(OnceCell::from("value") == OnceCell::from("value"));
75 assert!(OnceCell::from("foo") != OnceCell::from("bar"));
77 assert!(OnceCell::<&'static str>::new() == OnceCell::new());
78 assert!(OnceCell::<&'static str>::new() != OnceCell::from("value"));
83 let cell: OnceCell<&'static str> = OnceCell::new();
84 assert_eq!(cell.into_inner(), None);
85 let cell = OnceCell::new();
86 cell.set("hello").unwrap();
87 assert_eq!(cell.into_inner(), Some("hello"));
92 let called = Cell::new(0);
93 let x = LazyCell::new(|| {
94 called.set(called.get() + 1);
98 assert_eq!(called.get(), 0);
102 assert_eq!(called.get(), 1);
106 assert_eq!(called.get(), 1);
110 fn aliasing_in_get() {
111 let x = OnceCell::new();
113 let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option<T>` --+
114 let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option<T>` |
115 println!("{at_x}"); // <------- up until here ---------------------------+
119 #[should_panic(expected = "reentrant init")]
120 fn reentrant_init() {
121 let x: OnceCell<Box<i32>> = OnceCell::new();
122 let dangling_ref: Cell<Option<&i32>> = Cell::new(None);
124 let r = x.get_or_init(|| Box::new(92));
125 dangling_ref.set(Some(r));
128 eprintln!("use after free: {:?}", dangling_ref.get().unwrap());
133 let cell = OnceCell::new();
135 let s = String::new();
136 cell.set(&s).unwrap();