| 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 | extern crate core; |
| 9 | extern crate std; |
| 10 | |
| 11 | use self::std::cell::Cell; |
| 12 | use self::std::mem::MaybeUninit; |
| 13 | use self::std::prelude::v1::*; |
| 14 | use self::std::sync::Once; |
| 15 | #[allow (deprecated)] |
| 16 | pub use self::std::sync::ONCE_INIT; |
| 17 | |
| 18 | #[allow (dead_code)] // Used in macros |
| 19 | pub struct Lazy<T: Sync>(Cell<MaybeUninit<T>>, Once); |
| 20 | |
| 21 | impl<T: Sync> Lazy<T> { |
| 22 | #[allow (deprecated)] |
| 23 | pub const INIT: Self = Lazy(Cell::new(MaybeUninit::uninit()), ONCE_INIT); |
| 24 | |
| 25 | #[inline (always)] |
| 26 | pub fn get<F>(&'static self, f: F) -> &T |
| 27 | where |
| 28 | F: FnOnce() -> T, |
| 29 | { |
| 30 | self.1.call_once(|| { |
| 31 | self.0.set(val:MaybeUninit::new(val:f())); |
| 32 | }); |
| 33 | |
| 34 | // `self.0` is guaranteed to be initialized by this point |
| 35 | // The `Once` will catch and propagate panics |
| 36 | unsafe { &*(*self.0.as_ptr()).as_ptr() } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | unsafe impl<T: Sync> Sync for Lazy<T> {} |
| 41 | |
| 42 | #[macro_export ] |
| 43 | #[doc (hidden)] |
| 44 | macro_rules! __lazy_static_create { |
| 45 | ($NAME:ident, $T:ty) => { |
| 46 | static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::INIT; |
| 47 | }; |
| 48 | } |
| 49 | |