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();
52 let s = OnceCell::new();
54 assert!(c.get().is_none());
56 s.set("hello").unwrap();
58 assert_eq!(c.get().map(|c| *c), Some("hello"));
63 assert_eq!(OnceCell::from("value").get(), Some(&"value"));
64 assert_ne!(OnceCell::from("foo").get(), Some(&"bar"));
69 assert!(OnceCell::from("value") == OnceCell::from("value"));
70 assert!(OnceCell::from("foo") != OnceCell::from("bar"));
72 assert!(OnceCell::<&'static str>::new() == OnceCell::new());
73 assert!(OnceCell::<&'static str>::new() != OnceCell::from("value"));
78 let cell: OnceCell<&'static str> = OnceCell::new();
79 assert_eq!(cell.into_inner(), None);
80 let cell = OnceCell::new();
81 cell.set("hello").unwrap();
82 assert_eq!(cell.into_inner(), Some("hello"));
87 let called = Cell::new(0);
88 let x = Lazy::new(|| {
89 called.set(called.get() + 1);
93 assert_eq!(called.get(), 0);
97 assert_eq!(called.get(), 1);
101 assert_eq!(called.get(), 1);
105 fn aliasing_in_get() {
106 let x = OnceCell::new();
108 let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option<T>` --+
109 let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option<T>` |
110 println!("{}", at_x); // <------- up until here ---------------------------+
114 #[should_panic(expected = "reentrant init")]
115 fn reentrant_init() {
116 let x: OnceCell<Box<i32>> = OnceCell::new();
117 let dangling_ref: Cell<Option<&i32>> = Cell::new(None);
119 let r = x.get_or_init(|| Box::new(92));
120 dangling_ref.set(Some(r));
123 eprintln!("use after free: {:?}", dangling_ref.get().unwrap());
128 let cell = OnceCell::new();
130 let s = String::new();
131 cell.set(&s).unwrap();