forked from rust-lang-nursery/lazy-static.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy.rs
57 lines (48 loc) · 1.24 KB
/
lazy.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::sync::Once;
#[cfg(not(feature="nightly"))]
use std::mem::transmute;
#[cfg(feature="nightly")]
use std::cell::UnsafeCell;
#[cfg(feature="nightly")]
use std::sync::ONCE_INIT;
#[cfg(feature="nightly")]
pub struct Lazy<T: Sync>(UnsafeCell<Option<T>>, Once);
#[cfg(not(feature="nightly"))]
pub struct Lazy<T: Sync>(pub *const T, pub Once);
#[cfg(feature="nightly")]
impl<T: Sync> Lazy<T> {
#[inline(always)]
pub const fn new() -> Self {
Lazy(UnsafeCell::new(None), ONCE_INIT)
}
#[inline(always)]
pub fn get<F>(&'static self, f: F) -> &T
where F: FnOnce() -> T
{
unsafe {
self.1.call_once(|| {
*self.0.get() = Some(f());
});
match *self.0.get() {
Some(ref x) => x,
None => ::std::intrinsics::unreachable(),
}
}
}
}
#[cfg(not(feature="nightly"))]
impl<T: Sync> Lazy<T> {
#[inline(always)]
pub fn get<F>(&'static mut self, f: F) -> &T
where F: FnOnce() -> T
{
unsafe {
let r = &mut self.0;
self.1.call_once(|| {
*r = transmute(Box::new(f()));
});
&*self.0
}
}
}
unsafe impl<T: Sync> Sync for Lazy<T> {}