Skip to main content

qubit_function/mutators/mutator/
rc_mutator.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `RcMutator` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// 4. RcMutator - Single-Threaded Shared Ownership Implementation
17// ============================================================================
18
19/// RcMutator struct
20///
21/// A stateless mutator implementation based on `Rc<dyn Fn(&mut T)>` for
22/// single-threaded shared ownership scenarios. This type allows multiple
23/// references to the same mutator without the overhead of thread safety.
24///
25/// # Features
26///
27/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
28/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
29/// - **Stateless**: Cannot modify captured environment (uses `Fn` not `FnMut`)
30/// - **Chainable**: Method chaining via `&self` (non-consuming)
31/// - **Performance**: More efficient than `ArcMutator` (no locking)
32///
33/// # Use Cases
34///
35/// Choose `RcMutator` when:
36/// - The mutator needs to be shared within a single thread for stateless operations
37/// - Thread safety is not required
38/// - Performance is important (avoiding lock overhead)
39///
40/// # Examples
41///
42/// ```rust
43/// use qubit_function::{Mutator, RcMutator};
44///
45/// let mutator = RcMutator::new(|x: &mut i32| *x *= 2);
46/// let clone = mutator.clone();
47///
48/// let mut value = 5;
49/// mutator.apply(&mut value);
50/// assert_eq!(value, 10);
51/// ```
52///
53/// # Author
54///
55/// Haixing Hu
56pub struct RcMutator<T> {
57    pub(super) function: RcMutatorFn<T>,
58    pub(super) name: Option<String>,
59}
60
61impl<T> RcMutator<T> {
62    // Generate common mutator methods (new, new_with_name, name, set_name, noop)
63    impl_mutator_common_methods!(RcMutator<T>, (Fn(&mut T) + 'static), |f| Rc::new(f));
64
65    // Generate shared mutator methods (when, and_then, or_else, conversions)
66    impl_shared_mutator_methods!(
67        RcMutator<T>,
68        RcConditionalMutator,
69        into_rc,
70        Mutator,
71        'static
72    );
73}
74
75impl<T> Mutator<T> for RcMutator<T> {
76    fn apply(&self, value: &mut T) {
77        (self.function)(value)
78    }
79
80    // Generate all conversion methods using the unified macro
81    impl_rc_conversions!(
82        RcMutator<T>,
83        BoxMutator,
84        BoxMutatorOnce,
85        Fn(t: &mut T)
86    );
87}
88
89// Generate Clone trait implementation for mutator
90impl_mutator_clone!(RcMutator<T>);
91
92// Generate Debug and Display trait implementations
93impl_mutator_debug_display!(RcMutator<T>);