3 sync
::atomic
::{AtomicUsize, Ordering::SeqCst}
,
7 use once_cell
::sync
::{Lazy, OnceCell}
;
11 let called
= AtomicUsize
::new(0);
12 let x
= Lazy
::new(|| {
13 called
.fetch_add(1, SeqCst
);
17 assert_eq
!(called
.load(SeqCst
), 0);
23 assert_eq
!(called
.load(SeqCst
), 1);
29 assert_eq
!(called
.load(SeqCst
), 1);
34 let called
= AtomicUsize
::new(0);
35 let mut x
= Lazy
::new(|| {
36 called
.fetch_add(1, SeqCst
);
40 assert_eq
!(called
.load(SeqCst
), 0);
44 assert_eq
!(called
.load(SeqCst
), 1);
48 assert_eq
!(called
.load(SeqCst
), 1);
53 let called
= Cell
::new(0);
54 let mut x
= Lazy
::new(|| {
55 called
.set(called
.get() + 1);
58 assert_eq
!(called
.get(), 0);
59 let v
= Lazy
::force_mut(&mut x
);
60 assert_eq
!(called
.get(), 1);
64 assert_eq
!(called
.get(), 1);
69 let called
= Cell
::new(0);
70 let mut x
: Lazy
<u32, _
> = Lazy
::new(|| {
71 called
.set(called
.get() + 1);
75 assert_eq
!(called
.get(), 0);
78 let mut_ref
: &mut u32 = Lazy
::get_mut(&mut x
).unwrap();
79 assert_eq
!(called
.get(), 1);
83 assert_eq
!(called
.get(), 1);
88 static CALLED
: AtomicUsize
= AtomicUsize
::new(0);
91 impl Default
for Foo
{
92 fn default() -> Self {
93 CALLED
.fetch_add(1, SeqCst
);
98 let lazy
: Lazy
<std
::sync
::Mutex
<Foo
>> = <_
>::default();
100 assert_eq
!(CALLED
.load(SeqCst
), 0);
102 assert_eq
!(lazy
.lock().unwrap().0, 42);
103 assert_eq
!(CALLED
.load(SeqCst
), 1);
105 lazy
.lock().unwrap().0 = 21;
107 assert_eq
!(lazy
.lock().unwrap().0, 21);
108 assert_eq
!(CALLED
.load(SeqCst
), 1);
113 static XS
: Lazy
<Vec
<i32>> = Lazy
::new(|| {
114 let mut xs
= Vec
::new();
122 assert_eq
!(&*XS
, &vec
![1, 2, 3]);
125 assert_eq
!(&*XS
, &vec
![1, 2, 3]);
129 fn static_lazy_via_fn() {
130 fn xs() -> &'
static Vec
<i32> {
131 static XS
: OnceCell
<Vec
<i32>> = OnceCell
::new();
133 let mut xs
= Vec
::new();
140 assert_eq
!(xs(), &vec
![1, 2, 3]);
144 fn lazy_into_value() {
145 let l
: Lazy
<i32, _
> = Lazy
::new(|| panic
!());
146 assert
!(matches
!(Lazy
::into_value(l
), Err(_
)));
147 let l
= Lazy
::new(|| -> i32 { 92 }
);
149 assert
!(matches
!(Lazy
::into_value(l
), Ok(92)));
153 fn lazy_poisoning() {
154 let x
: Lazy
<String
> = Lazy
::new(|| panic
!("kaboom"));
156 let res
= std
::panic
::catch_unwind(|| x
.len());
157 assert
!(res
.is_err());
162 // https://github.com/rust-lang/rust/issues/34761#issuecomment-256320669
163 fn arrrrrrrrrrrrrrrrrrrrrr() {
164 let lazy
: Lazy
<&String
, _
>;
166 let s
= String
::new();
167 lazy
= Lazy
::new(|| &s
);
173 fn lazy_is_sync_send() {
174 fn assert_traits
<T
: Send
+ Sync
>() {}
175 assert_traits
::<Lazy
<String
>>();