1 use core::{
2 cell::Cell,
3 sync::atomic::{AtomicUsize, Ordering::SeqCst},
4 };
5
6 use once_cell::unsync::OnceCell;
7
8 #[test]
once_cell()9 fn once_cell() {
10 let c = OnceCell::new();
11 assert!(c.get().is_none());
12 c.get_or_init(|| 92);
13 assert_eq!(c.get(), Some(&92));
14
15 c.get_or_init(|| panic!("Kabom!"));
16 assert_eq!(c.get(), Some(&92));
17 }
18
19 #[test]
once_cell_with_value()20 fn once_cell_with_value() {
21 const CELL: OnceCell<i32> = OnceCell::with_value(12);
22 let cell = CELL;
23 assert_eq!(cell.get(), Some(&12));
24 }
25
26 #[test]
once_cell_get_mut()27 fn once_cell_get_mut() {
28 let mut c = OnceCell::new();
29 assert!(c.get_mut().is_none());
30 c.set(90).unwrap();
31 *c.get_mut().unwrap() += 2;
32 assert_eq!(c.get_mut(), Some(&mut 92));
33 }
34
35 #[test]
once_cell_drop()36 fn once_cell_drop() {
37 static DROP_CNT: AtomicUsize = AtomicUsize::new(0);
38 struct Dropper;
39 impl Drop for Dropper {
40 fn drop(&mut self) {
41 DROP_CNT.fetch_add(1, SeqCst);
42 }
43 }
44
45 let x = OnceCell::new();
46 x.get_or_init(|| Dropper);
47 assert_eq!(DROP_CNT.load(SeqCst), 0);
48 drop(x);
49 assert_eq!(DROP_CNT.load(SeqCst), 1);
50 }
51
52 #[test]
once_cell_drop_empty()53 fn once_cell_drop_empty() {
54 let x = OnceCell::<String>::new();
55 drop(x);
56 }
57
58 #[test]
clone()59 fn clone() {
60 let s = OnceCell::new();
61 let c = s.clone();
62 assert!(c.get().is_none());
63
64 s.set("hello".to_string()).unwrap();
65 let c = s.clone();
66 assert_eq!(c.get().map(String::as_str), Some("hello"));
67 }
68
69 #[test]
70 #[cfg(not(target_os = "android"))]
get_or_try_init()71 fn get_or_try_init() {
72 let cell: OnceCell<String> = OnceCell::new();
73 assert!(cell.get().is_none());
74
75 let res = std::panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() }));
76 assert!(res.is_err());
77 assert!(cell.get().is_none());
78
79 assert_eq!(cell.get_or_try_init(|| Err(())), Err(()));
80
81 assert_eq!(cell.get_or_try_init(|| Ok::<_, ()>("hello".to_string())), Ok(&"hello".to_string()));
82 assert_eq!(cell.get(), Some(&"hello".to_string()));
83 }
84
85 #[test]
from_impl()86 fn from_impl() {
87 assert_eq!(OnceCell::from("value").get(), Some(&"value"));
88 assert_ne!(OnceCell::from("foo").get(), Some(&"bar"));
89 }
90
91 #[test]
partialeq_impl()92 fn partialeq_impl() {
93 assert!(OnceCell::from("value") == OnceCell::from("value"));
94 assert!(OnceCell::from("foo") != OnceCell::from("bar"));
95
96 assert!(OnceCell::<String>::new() == OnceCell::new());
97 assert!(OnceCell::<String>::new() != OnceCell::from("value".to_owned()));
98 }
99
100 #[test]
into_inner()101 fn into_inner() {
102 let cell: OnceCell<String> = OnceCell::new();
103 assert_eq!(cell.into_inner(), None);
104 let cell = OnceCell::new();
105 cell.set("hello".to_string()).unwrap();
106 assert_eq!(cell.into_inner(), Some("hello".to_string()));
107 }
108
109 #[test]
debug_impl()110 fn debug_impl() {
111 let cell = OnceCell::new();
112 assert_eq!(format!("{:#?}", cell), "OnceCell(Uninit)");
113 cell.set(vec!["hello", "world"]).unwrap();
114 assert_eq!(
115 format!("{:#?}", cell),
116 r#"OnceCell(
117 [
118 "hello",
119 "world",
120 ],
121 )"#
122 );
123 }
124
125 #[test]
126 #[should_panic(expected = "reentrant init")]
127 #[ignore = "Android: ignore for now. Need to compile these binaries separately."]
reentrant_init()128 fn reentrant_init() {
129 let x: OnceCell<Box<i32>> = OnceCell::new();
130 let dangling_ref: Cell<Option<&i32>> = Cell::new(None);
131 x.get_or_init(|| {
132 let r = x.get_or_init(|| Box::new(92));
133 dangling_ref.set(Some(r));
134 Box::new(62)
135 });
136 eprintln!("use after free: {:?}", dangling_ref.get().unwrap());
137 }
138
139 #[test]
aliasing_in_get()140 fn aliasing_in_get() {
141 let x = OnceCell::new();
142 x.set(42).unwrap();
143 let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option<T>` --+
144 let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option<T>` |
145 println!("{}", at_x); // <------- up until here ---------------------------+
146 }
147
148 #[test]
149 // https://github.com/rust-lang/rust/issues/34761#issuecomment-256320669
arrrrrrrrrrrrrrrrrrrrrr()150 fn arrrrrrrrrrrrrrrrrrrrrr() {
151 let cell = OnceCell::new();
152 {
153 let s = String::new();
154 cell.set(&s).unwrap();
155 }
156 }
157