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