Skip to content

Instantly share code, notes, and snippets.

Created April 15, 2016 00:30
Show Gist options
  • Save anonymous/7fb56ee443b91f3c57ab45e4863ce004 to your computer and use it in GitHub Desktop.
Save anonymous/7fb56ee443b91f3c57ab45e4863ce004 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::sync::Once;
pub struct Lazy<T: Sync>(pub *const T, pub Once);
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 = Box::into_raw(Box::new(f()));
});
&*self.0
}
}
}
unsafe impl<T: Sync> Sync for Lazy<T> {}
#[macro_export]
macro_rules! __lazy_static_create {
($NAME:ident, $T:ty) => {
use std::sync::ONCE_INIT;
static mut $NAME: Lazy<$T> = Lazy(0 as *const $T, ONCE_INIT);
}
}
macro_rules! lazy_static {
($(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
lazy_static!(@PRIV, $(#[$attr])* static ref $N : $T = $e; $($t)*);
};
($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
lazy_static!(@PUB, $(#[$attr])* static ref $N : $T = $e; $($t)*);
};
(@$VIS:ident, $(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
lazy_static!(@MAKE TY, $VIS, $(#[$attr])*, $N);
impl ::std::ops::Deref for $N {
type Target = $T;
#[allow(unsafe_code)]
fn deref<'a>(&'a self) -> &'a $T {
unsafe {
#[inline(always)]
fn __static_ref_initialize() -> $T { $e }
#[inline(always)]
unsafe fn __stability() -> &'static $T {
__lazy_static_create!(LAZY, $T);
LAZY.get(__static_ref_initialize)
}
__stability()
}
}
}
lazy_static!($($t)*);
};
(@MAKE TY, PUB, $(#[$attr:meta])*, $N:ident) => {
#[allow(missing_copy_implementations)]
#[allow(non_camel_case_types)]
#[allow(dead_code)]
$(#[$attr])*
pub struct $N {__private_field: ()}
#[doc(hidden)]
pub static $N: $N = $N {__private_field: ()};
};
(@MAKE TY, PRIV, $(#[$attr:meta])*, $N:ident) => {
#[allow(missing_copy_implementations)]
#[allow(non_camel_case_types)]
#[allow(dead_code)]
$(#[$attr])*
struct $N {__private_field: ()}
#[doc(hidden)]
static $N: $N = $N {__private_field: ()};
};
() => ()
}
lazy_static! {
/// EventUUID is used internally to index events, is randomly
/// generated at first access.
pub static ref EVENT_UUID: String = "asdf".to_string();
}
fn print_stuff(x: &'static String) { println!("{}",x)}
fn main() {
print_stuff(&*EVENT_UUID)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment