diff --git a/f9/src/app.rs b/f9/src/app.rs index 9e02478..6264a35 100644 --- a/f9/src/app.rs +++ b/f9/src/app.rs @@ -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 { diff --git a/r9_macro/src/lib.rs b/r9_macro/src/lib.rs index d11b016..ad1da38 100644 --- a/r9_macro/src/lib.rs +++ b/r9_macro/src/lib.rs @@ -13,3 +13,7 @@ mod tests { pub trait SharedFromSelf { fn shared_from_self(&self) -> Rc::>; } + +pub trait Singleton { + fn instance() -> Rc::>; +} diff --git a/r9_macro_derive/src/lib.rs b/r9_macro_derive/src/lib.rs index 33b97b2..6b90edf 100644 --- a/r9_macro_derive/src/lib.rs +++ b/r9_macro_derive/src/lib.rs @@ -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::> { + static mut _INSTANCE: Option>> = 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() +}