lazy_static/lib.rs
1// Copyright 2016 lazy-static.rs Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8/*!
9<div class="warning">
10
11This crate has been replaced by the [`LazyLock`] type, which is stable since Rust 1.80.0 with a slightly different syntax. Barring breakages and security fixes, this crate will no longer be updated.
12
13[`LazyLock`]: https://doc.rust-lang.org/std/sync/struct.LazyLock.html
14
15</div>
16
17A macro for declaring lazily evaluated statics.
18
19Using this macro, it is possible to have `static`s that require code to be
20executed at runtime in order to be initialized.
21This includes anything requiring heap allocations, like vectors or hash maps,
22as well as anything that requires function calls to be computed.
23
24# Syntax
25
26```ignore
27lazy_static! {
28 [pub] static ref NAME_1: TYPE_1 = EXPR_1;
29 [pub] static ref NAME_2: TYPE_2 = EXPR_2;
30 ...
31 [pub] static ref NAME_N: TYPE_N = EXPR_N;
32}
33```
34
35Attributes (including doc comments) are supported as well:
36
37```rust
38use lazy_static::lazy_static;
39
40# fn main() {
41lazy_static! {
42 /// This is an example of using doc comment attributes
43 static ref EXAMPLE: u8 = 42;
44}
45# }
46```
47
48# Semantics
49
50For a given `static ref NAME: TYPE = EXPR;`, the macro generates a unique type that
51implements `Deref<TYPE>` and stores it in a static with name `NAME`. (Attributes end up
52attaching to this type.)
53
54On first deref, `EXPR` gets evaluated and stored internally, such that all further derefs
55can return a reference to the same object. Note that this can lead to deadlocks
56if you have multiple lazy statics that depend on each other in their initialization.
57
58Apart from the lazy initialization, the resulting "static ref" variables
59have generally the same properties as regular "static" variables:
60
61- Any type in them needs to fulfill the `Sync` trait.
62- If the type has a destructor, then it will not run when the process exits.
63
64# Example
65
66Using the macro:
67
68```rust
69use lazy_static::lazy_static;
70use std::collections::HashMap;
71
72lazy_static! {
73 static ref HASHMAP: HashMap<u32, &'static str> = {
74 let mut m = HashMap::new();
75 m.insert(0, "foo");
76 m.insert(1, "bar");
77 m.insert(2, "baz");
78 m
79 };
80 static ref COUNT: usize = HASHMAP.len();
81 static ref NUMBER: u32 = times_two(21);
82}
83
84fn times_two(n: u32) -> u32 { n * 2 }
85
86fn main() {
87 println!("The map has {} entries.", *COUNT);
88 println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());
89 println!("A expensive calculation on a static results in: {}.", *NUMBER);
90}
91```
92
93# Implementation details
94
95The `Deref` implementation uses a hidden static variable that is guarded by an atomic check on each access.
96
97# Cargo features
98
99This crate provides one cargo feature:
100
101- `spin_no_std`: This allows using this crate in a no-std environment, by depending on the standalone `spin` crate.
102
103*/
104
105#![doc(html_root_url = "https://docs.rs/lazy_static/1.5.1")]
106#![no_std]
107
108#[cfg(doctest)]
109#[macro_use]
110extern crate doc_comment;
111
112#[cfg(doctest)]
113doctest!("../README.md");
114
115#[cfg_attr(feature = "spin_no_std", path = "core_lazy.rs")]
116#[cfg_attr(not(feature = "spin_no_std"), path = "inline_lazy.rs")]
117#[doc(hidden)]
118pub mod lazy;
119
120#[doc(hidden)]
121pub use core::ops::Deref as __Deref;
122
123#[macro_export(local_inner_macros)]
124#[doc(hidden)]
125macro_rules! __lazy_static_internal {
126 // optional visibility restrictions are wrapped in `()` to allow for
127 // explicitly passing otherwise implicit information about private items
128 ($(#[$attr:meta])* ($($vis:tt)*) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
129 __lazy_static_internal!(@MAKE TY, $(#[$attr])*, ($($vis)*), $N);
130 __lazy_static_internal!(@TAIL, $N : $T = $e);
131 lazy_static!($($t)*);
132 };
133 (@TAIL, $N:ident : $T:ty = $e:expr) => {
134 impl $crate::__Deref for $N {
135 type Target = $T;
136 fn deref(&self) -> &$T {
137 #[inline(always)]
138 fn __static_ref_initialize() -> $T { $e }
139
140 #[inline(always)]
141 fn __stability() -> &'static $T {
142 __lazy_static_create!(LAZY, $T);
143 LAZY.get(__static_ref_initialize)
144 }
145 __stability()
146 }
147 }
148 impl $crate::LazyStatic for $N {
149 fn initialize(lazy: &Self) {
150 let _ = &**lazy;
151 }
152 }
153 };
154 // `vis` is wrapped in `()` to prevent parsing ambiguity
155 (@MAKE TY, $(#[$attr:meta])*, ($($vis:tt)*), $N:ident) => {
156 #[allow(missing_copy_implementations)]
157 #[allow(non_camel_case_types)]
158 #[allow(dead_code)]
159 $(#[$attr])*
160 $($vis)* struct $N {__private_field: ()}
161 #[doc(hidden)]
162 #[allow(non_upper_case_globals)]
163 $($vis)* static $N: $N = $N {__private_field: ()};
164 };
165 () => ()
166}
167
168#[macro_export(local_inner_macros)]
169macro_rules! lazy_static {
170 ($(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
171 // use `()` to explicitly forward the information about private items
172 __lazy_static_internal!($(#[$attr])* () static ref $N : $T = $e; $($t)*);
173 };
174 ($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
175 __lazy_static_internal!($(#[$attr])* (pub) static ref $N : $T = $e; $($t)*);
176 };
177 ($(#[$attr:meta])* pub ($($vis:tt)+) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
178 __lazy_static_internal!($(#[$attr])* (pub ($($vis)+)) static ref $N : $T = $e; $($t)*);
179 };
180 () => ()
181}
182
183/// Support trait for enabling a few common operations on lazy static values.
184///
185/// This is implemented by each defined lazy static, and
186/// used by the free functions in this crate.
187pub trait LazyStatic {
188 #[doc(hidden)]
189 fn initialize(lazy: &Self);
190}
191
192/// Takes a shared reference to a lazy static and initializes
193/// it if it has not been already.
194///
195/// This can be used to control the initialization point of a lazy static.
196///
197/// Example:
198///
199/// ```rust
200/// use lazy_static::lazy_static;
201///
202/// lazy_static! {
203/// static ref BUFFER: Vec<u8> = (0..255).collect();
204/// }
205///
206/// fn main() {
207/// lazy_static::initialize(&BUFFER);
208///
209/// // ...
210/// work_with_initialized_data(&BUFFER);
211/// }
212/// # fn work_with_initialized_data(_: &[u8]) {}
213/// ```
214pub fn initialize<T: LazyStatic>(lazy: &T) {
215 LazyStatic::initialize(lazy);
216}