qubit_function/macros/common_new_methods.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9
10//! # Common New Methods Macro
11//!
12//! Generates common constructor methods for function-like structs.
13//!
14//! # Author
15//!
16//! Haixing Hu
17
18/// Implements common constructor methods for function-like structs.
19///
20/// This macro generates `new`, `new_with_name`, and `new_with_optional_name`
21/// methods for structs that wrap function pointers or closures. It provides
22/// a standardized way to create instances with or without names for debugging
23/// and logging purposes.
24///
25/// # Parameters
26///
27/// * `$($fn_trait_with_bounds)+` - Function trait bounds (e.g., Fn(i32) -> i32)
28/// * `$f:ident` - Identifier for the function parameter
29/// * `$wrapper_expr:expr` - Expression to wrap the function (e.g., Arc::new(f))
30/// * `$type_desc:literal` - Description of the type (e.g., "consumer")
31///
32/// # Generated Methods
33///
34/// * `new<F>(f: F) -> Self` - Creates a new instance without a name
35/// * `new_with_name<F>(name: &str, f: F) -> Self` - Creates a named instance
36/// * `new_with_optional_name<F>(f: F, name: Option<String>) -> Self` -
37/// Creates an instance with an optional name
38///
39/// # Author
40///
41/// Haixing Hu
42macro_rules! impl_common_new_methods {
43 (
44 ($($fn_trait_with_bounds:tt)+),
45 |$f:ident| $wrapper_expr:expr,
46 $type_desc:literal
47 ) => {
48 #[doc = concat!("Creates a new ", $type_desc, ".")]
49 ///
50 #[doc = concat!("Wraps the provided closure in the appropriate smart pointer type for this ", $type_desc, " implementation.")]
51 #[inline]
52 pub fn new<F>($f: F) -> Self
53 where
54 F: $($fn_trait_with_bounds)+,
55 {
56 Self {
57 function: $wrapper_expr,
58 name: None,
59 }
60 }
61
62 #[doc = concat!("Creates a new named ", $type_desc, ".")]
63 ///
64 /// Wraps the provided closure and assigns it a name, which is
65 /// useful for debugging and logging purposes.
66 #[inline]
67 pub fn new_with_name<F>(name: &str, $f: F) -> Self
68 where
69 F: $($fn_trait_with_bounds)+,
70 {
71 Self {
72 function: $wrapper_expr,
73 name: Some(name.to_string()),
74 }
75 }
76
77 #[doc = concat!("Creates a new named ", $type_desc, " with an optional name.")]
78 ///
79 /// Wraps the provided closure and assigns it an optional name.
80 #[inline]
81 pub fn new_with_optional_name<F>($f: F, name: Option<String>) -> Self
82 where
83 F: $($fn_trait_with_bounds)+,
84 {
85 Self {
86 function: $wrapper_expr,
87 name,
88 }
89 }
90 };
91}
92
93pub(crate) use impl_common_new_methods;