singleton_registry/
macros.rs

1#![allow(dead_code)]
2
3//! Macros for creating singleton registries.
4//!
5//! This module provides a simple macro-based approach to create type-safe,
6//! thread-safe singleton registries with zero external dependencies.
7
8/// Creates a singleton registry module with ergonomic free functions.
9///
10/// The macro generates a module containing storage, tracing infrastructure,
11/// and a private `Api` struct implementing `RegistryApi`.
12///
13/// # Example
14///
15/// ```rust
16/// use singleton_registry::define_registry;
17/// use std::sync::Arc;
18///
19/// // Create registries - each is isolated
20/// define_registry!(global);
21/// define_registry!(cache);
22///
23/// // Register and retrieve values
24/// global::register(42i32);
25/// cache::register("redis".to_string());
26///
27/// let num: Arc<i32> = global::get().unwrap();
28/// let msg: Arc<String> = cache::get().unwrap();
29///
30/// assert_eq!(*num, 42);
31/// assert_eq!(&**msg, "redis");
32/// ```
33#[macro_export]
34macro_rules! define_registry {
35    ($name:ident) => {
36        pub mod $name {
37            use std::sync::{Arc, LazyLock, Mutex};
38            use std::collections::HashMap;
39            use std::any::{TypeId, Any};
40
41            // Storage for registered values (module-private)
42            static STORAGE: LazyLock<Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>> =
43                LazyLock::new(|| Mutex::new(HashMap::new()));
44
45            // Trace callback storage (module-private)
46            // Note: This type matches TraceCallback in registry_trait.rs - keep in sync
47            type TraceCallback = LazyLock<Mutex<Option<Arc<dyn Fn(&$crate::RegistryEvent) + Send + Sync>>>>;
48            static TRACE: TraceCallback = LazyLock::new(|| Mutex::new(None));
49
50            /// Zero-sized type that implements the registry API.
51            ///
52            /// All registry operations are provided by the `RegistryApi` trait's
53            /// default implementations. This struct only provides access to the statics.
54            struct Api;
55
56            impl $crate::RegistryApi for Api {
57                fn storage() -> &'static LazyLock<Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>> {
58                    &STORAGE
59                }
60
61                fn trace() -> &'static TraceCallback {
62                    &TRACE
63                }
64
65                // All other methods (register, get, contains, etc.) are provided by
66                // the trait's default implementations!
67            }
68
69            /// Convenient constant for accessing the registry API.
70            const API: Api = Api;
71
72            // Free functions for ergonomic usage - they delegate to API
73
74            /// Register a value in the registry.
75            pub fn register<T: Send + Sync + 'static>(value: T) {
76                use $crate::RegistryApi;
77                API.register(value)
78            }
79
80            /// Register an Arc-wrapped value in the registry.
81            pub fn register_arc<T: Send + Sync + 'static>(value: Arc<T>) {
82                use $crate::RegistryApi;
83                API.register_arc(value)
84            }
85
86            /// Retrieve a value from the registry.
87            pub fn get<T: Send + Sync + 'static>() -> Result<Arc<T>, $crate::RegistryError> {
88                use $crate::RegistryApi;
89                API.get()
90            }
91
92            /// Retrieve a cloned value from the registry.
93            pub fn get_cloned<T: Send + Sync + Clone + 'static>() -> Result<T, $crate::RegistryError> {
94                use $crate::RegistryApi;
95                API.get_cloned()
96            }
97
98            /// Check if a type is registered in the registry.
99            pub fn contains<T: Send + Sync + 'static>() -> Result<bool, $crate::RegistryError> {
100                use $crate::RegistryApi;
101                API.contains::<T>()
102            }
103
104            /// Set a tracing callback for registry operations.
105            pub fn set_trace_callback(callback: impl Fn(&$crate::RegistryEvent) + Send + Sync + 'static) {
106                use $crate::RegistryApi;
107                API.set_trace_callback(callback)
108            }
109
110            /// Clear the tracing callback.
111            pub fn clear_trace_callback() {
112                use $crate::RegistryApi;
113                API.clear_trace_callback()
114            }
115
116            /// Clear the registry.
117            #[doc(hidden)]
118            pub fn clear() {
119                use $crate::RegistryApi;
120                API.clear()
121            }
122        }
123    };
124}
125
126#[cfg(test)]
127mod tests {
128    // use crate::RegistryApi;
129    use std::sync::Arc;
130
131    #[test]
132    fn test_define_registry_macro() {
133        define_registry!(test_reg);
134
135        // Test register and get (ergonomic free functions)
136        test_reg::register(100i32);
137        let value: Arc<i32> = test_reg::get().unwrap();
138        assert_eq!(*value, 100);
139
140        // Test contains
141        assert!(test_reg::contains::<i32>().unwrap());
142        assert!(!test_reg::contains::<f64>().unwrap());
143    }
144
145    #[test]
146    fn test_multiple_registries() {
147        define_registry!(reg_a);
148        define_registry!(reg_b);
149
150        // Register different values in each
151        reg_a::register(1i32);
152        reg_b::register(2i32);
153
154        // Verify isolation
155        let a_val: Arc<i32> = reg_a::get().unwrap();
156        let b_val: Arc<i32> = reg_b::get().unwrap();
157
158        assert_eq!(*a_val, 1);
159        assert_eq!(*b_val, 2);
160    }
161
162    #[test]
163    fn test_tracing() {
164        define_registry!(trace_test);
165
166        use std::sync::Mutex;
167        let events = Arc::new(Mutex::new(Vec::new()));
168        let events_clone = events.clone();
169
170        trace_test::set_trace_callback(move |event| {
171            events_clone.lock().unwrap().push(format!("{}", event));
172        });
173
174        trace_test::register(42i32);
175        let _: Arc<i32> = trace_test::get().unwrap();
176        let _ = trace_test::contains::<i32>();
177
178        let recorded = events.lock().unwrap();
179        assert_eq!(recorded.len(), 3);
180        assert!(recorded[0].contains("register"));
181        assert!(recorded[1].contains("get"));
182        assert!(recorded[2].contains("contains"));
183    }
184
185    #[test]
186    fn test_additional_functions() {
187        define_registry!(extra_test);
188
189        // Test register_arc
190        let val = Arc::new(99i32);
191        extra_test::register_arc(val);
192
193        // Test get_cloned
194        let cloned: i32 = extra_test::get_cloned().unwrap();
195        assert_eq!(cloned, 99);
196
197        // Test clear_trace_callback
198        extra_test::set_trace_callback(|_| {});
199        extra_test::clear_trace_callback(); // Just verify it doesn't panic
200    }
201}