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