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
8extern crate core;
9extern crate std;
10
11use self::std::cell::Cell;
12use self::std::mem::MaybeUninit;
13use self::std::prelude::v1::*;
14use self::std::sync::Once;
15#[allow(deprecated)]
16pub use self::std::sync::ONCE_INIT;
17
18#[allow(dead_code)] // Used in macros
19pub struct Lazy<T: Sync>(Cell<MaybeUninit<T>>, Once);
20
21impl<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
40unsafe impl<T: Sync> Sync for Lazy<T> {}
41
42#[macro_export]
43#[doc(hidden)]
44macro_rules! __lazy_static_create {
45 ($NAME:ident, $T:ty) => {
46 static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::INIT;
47 };
48}
49

Provided by KDAB

Privacy Policy
Learn Rust with the experts
Find out more