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
58
59
60
61
62
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;
use proc_macro::TokenStream;
#[proc_macro_derive(MakeSingleton)]
pub fn hello_world(input: TokenStream) -> TokenStream {
let s = input.to_string();
let ast = syn::parse_derive_input(&s).unwrap();
let gen = impl_make_singelton(&ast);
gen.parse().unwrap()
}
fn impl_make_singelton(ast: &syn::DeriveInput) -> quote::Tokens {
let name = &ast.ident;
quote! {
pub trait MakeSingletonTrait<T> {
fn instance_thread_safe() -> Arc<Mutex<T>>;
fn instance_ptr() -> *const T;
}
impl MakeSingletonTrait<#name> for #name {
fn instance_thread_safe() -> Arc<Mutex<#name>> {
unsafe {
static mut INSTANCE: *const Arc<Mutex<#name>> = 0 as *const Arc<Mutex<#name>>;
static ONCE: Once = Once::new();
ONCE.call_once(||{
let tmp_instance = Arc::new(Mutex::new(#name{}));
INSTANCE = mem::transmute(#name::instance_ptr());
});
(*INSTANCE).clone()
}
}
fn instance_ptr() -> *const #name {
unsafe {
static mut INSTANCE: *const #name = 0 as *const #name;
static ONCE: Once = Once::new();
ONCE.call_once(||{
let tmp_instance = #name{};
INSTANCE = mem::transmute(Box::new(tmp_instance));
});
INSTANCE
}
}
}
}
}