This commit is contained in:
azw 2023-10-29 09:37:52 +00:00
parent 07d53fe46e
commit 1add5d9388
3 changed files with 41 additions and 3 deletions

View File

@ -75,15 +75,15 @@ impl App {
}
pub fn get_instance_id(&self) -> i32 {
return 0;
return self.instance_id;
}
pub fn get_zone_id(&self) -> i32 {
return 0;
return self.zone_id;
}
pub fn get_node_id(&self) -> i32 {
return 0;
return self.node_id;
}
pub fn has_flag(&self) -> bool {

View File

@ -13,3 +13,7 @@ mod tests {
pub trait SharedFromSelf {
fn shared_from_self(&self) -> Rc::<RefCell::<Self>>;
}
pub trait Singleton {
fn instance() -> Rc::<RefCell::<Self>>;
}

View File

@ -31,3 +31,37 @@ fn impl_shared_from_self_macro(ast: &syn::DeriveInput) -> TokenStream {
};
gen.into()
}
#[proc_macro_derive(Singleton)]
pub fn singleton_derive(input: TokenStream) -> TokenStream {
let ast = syn::parse(input).unwrap();
// Build the trait implementation
impl_singleton_macro(&ast)
}
fn impl_singleton_macro(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let (impl_generics, _, _) = ast.generics.split_for_impl();
let gen = quote! {
impl #impl_generics Singleton for #name #impl_generics {
fn instance() -> Rc::<RefCell::<Self>> {
static mut _INSTANCE: Option<Rc::<RefCell::<#name>>> = None;
unsafe {
match &_INSTANCE {
Some(v) => {
return v.clone();
}
None => {
_INSTANCE = Some(Rc::new(RefCell::new(Self::new())));
_INSTANCE.clone().unwrap().borrow_mut()._self_wp =
Rc::downgrade(&_INSTANCE.clone().unwrap());
}
}
return _INSTANCE.clone().unwrap().clone();
}
}
}
};
gen.into()
}