35
35
36
36
Using the macro:
37
37
38
- ```rust
38
+ ```ignore
39
39
#[macro_use]
40
40
extern crate lazy_static;
41
41
@@ -71,6 +71,25 @@ The `Deref` implementation uses a hidden static variable that is guarded by a at
71
71
#![ cfg_attr( feature="nightly" , feature( const_fn, core_intrinsics) ) ]
72
72
#![ crate_type = "dylib" ]
73
73
74
+ pub mod lazy;
75
+
76
+ #[ cfg( feature="nightly" ) ]
77
+ #[ macro_export]
78
+ macro_rules! lazy_create {
79
+ ( $T: ty) => {
80
+ static LAZY : $crate:: lazy:: Lazy <$T> = $crate:: lazy:: Lazy :: new( ) ;
81
+ }
82
+ }
83
+
84
+ #[ cfg( not( feature="nightly" ) ) ]
85
+ #[ macro_export]
86
+ macro_rules! lazy_create {
87
+ ( $T: ty) => {
88
+ use std:: sync:: ONCE_INIT ;
89
+ static mut LAZY : $crate:: lazy:: Lazy <$T> = $crate:: lazy:: Lazy ( 0 as * const $T, ONCE_INIT ) ;
90
+ }
91
+ }
92
+
74
93
#[ macro_export]
75
94
macro_rules! lazy_static {
76
95
( $( #[ $attr: meta] ) * static ref $N: ident : $T: ty = $e: expr; $( $t: tt) * ) => {
@@ -84,51 +103,15 @@ macro_rules! lazy_static {
84
103
impl :: std:: ops:: Deref for $N {
85
104
type Target = $T;
86
105
fn deref<' a>( & ' a self ) -> & ' a $T {
87
- #[ inline( always) ]
88
- fn __static_ref_initialize( ) -> $T { $e }
89
-
90
106
unsafe {
91
- use std:: sync:: { Once , ONCE_INIT } ;
92
-
93
- #[ inline( always) ]
94
- fn require_sync<T : Sync >( _: & T ) { }
95
-
96
107
#[ inline( always) ]
97
- #[ cfg( feature="nightly" ) ]
98
- unsafe fn __stability( ) -> & ' static $T {
99
- use std:: cell:: UnsafeCell ;
100
-
101
- struct SyncCell ( UnsafeCell <Option <$T>>) ;
102
- unsafe impl Sync for SyncCell { }
103
-
104
- static DATA : SyncCell = SyncCell ( UnsafeCell :: new( None ) ) ;
105
- static ONCE : Once = ONCE_INIT ;
106
- ONCE . call_once( || {
107
- * DATA . 0 . get( ) = Some ( __static_ref_initialize( ) ) ;
108
- } ) ;
109
- match * DATA . 0 . get( ) {
110
- Some ( ref x) => x,
111
- None => :: std:: intrinsics:: unreachable( ) ,
112
- }
113
- }
108
+ fn __static_ref_initialize( ) -> $T { $e }
114
109
115
- #[ inline( always) ]
116
- #[ cfg( not( feature="nightly" ) ) ]
117
110
unsafe fn __stability( ) -> & ' static $T {
118
- use std:: mem:: transmute;
119
-
120
- static mut DATA : * const $T = 0 as * const $T;
121
- static mut ONCE : Once = ONCE_INIT ;
122
- ONCE . call_once( || {
123
- DATA = transmute:: <Box <$T>, * const $T>(
124
- Box :: new( __static_ref_initialize( ) ) ) ;
125
- } ) ;
126
- & * DATA
111
+ lazy_create!( $T) ;
112
+ LAZY . get( __static_ref_initialize)
127
113
}
128
-
129
- let static_ref = __stability( ) ;
130
- require_sync( static_ref) ;
131
- static_ref
114
+ __stability( )
132
115
}
133
116
}
134
117
}
0 commit comments