Skip to content

Commit f768757

Browse files
committed
Add a free initialize() function for manually pre-initializing a lazy static
1 parent a545f52 commit f768757

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

src/lib.rs

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ macro_rules! __lazy_static_internal {
130130
}
131131
}
132132
}
133+
impl $crate::LazyStatic for $N {
134+
fn initialize(lazy: &Self) {
135+
let _ = &*lazy;
136+
}
137+
}
133138
__lazy_static_internal!($($t)*);
134139
};
135140
(@MAKE TY, PUB, $(#[$attr:meta])*, $N:ident) => {
@@ -165,13 +170,38 @@ macro_rules! lazy_static {
165170
() => ()
166171
}
167172

168-
/*
169-
trait LazyStatic<T>: Deref<Target=T> {
170-
173+
/// Support trait for enabling a few common operation on lazy static values.
174+
///
175+
/// This is implemented by each defined lazy static, and
176+
/// used by the free functions in this crate.
177+
pub trait LazyStatic {
178+
#[doc(hidden)]
179+
fn initialize(lazy: &Self);
171180
}
172181

182+
/// Takes a shared reference to a lazy static and initializes
183+
/// it if it has not been already.
173184
///
174-
pub fn initialize<T>(lazy: &lazy::Lazy<T>) {
175-
185+
/// This can be used to control the initialization point of a lazy static.
186+
///
187+
/// Example:
188+
///
189+
/// ```rust
190+
/// #[macro_use]
191+
/// extern crate lazy_static;
192+
///
193+
/// lazy_static! {
194+
/// static ref BUFFER: Vec<u8> = (0..65537).collect();
195+
/// }
196+
///
197+
/// fn main() {
198+
/// lazy_static::initialize(&BUFFER);
199+
///
200+
/// // ...
201+
/// work_with_initialized_data(&BUFFER);
202+
/// }
203+
/// # fn work_with_initialized_data(_: &[u8]) {}
204+
/// ```
205+
pub fn initialize<T: LazyStatic>(lazy: &T) {
206+
LazyStatic::initialize(lazy);
176207
}
177-
*/

0 commit comments

Comments
 (0)