qubit_function/mutators/mutator/rc_conditional_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 `RcConditionalMutator` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// 9. RcConditionalMutator - Rc-based Conditional Mutator
17// ============================================================================
18
19/// RcConditionalMutator struct
20///
21/// A single-threaded conditional mutator that only executes when a predicate is
22/// satisfied. Uses `RcMutator` and `RcPredicate` for shared ownership within a
23/// single thread.
24///
25/// This type is typically created by calling `RcMutator::when()` and is
26/// designed to work with the `or_else()` method to create if-then-else logic.
27///
28/// # Features
29///
30/// - **Shared Ownership**: Cloneable via `Rc`, multiple owners allowed
31/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
32/// - **Conditional Execution**: Only mutates when predicate returns `true`
33/// - **No Lock Overhead**: More efficient than `ArcConditionalMutator`
34///
35/// # Examples
36///
37/// ```rust
38/// use qubit_function::{Mutator, RcMutator};
39///
40/// let conditional = RcMutator::new(|x: &mut i32| *x *= 2)
41/// .when(|x: &i32| *x > 0);
42///
43/// let conditional_clone = conditional.clone();
44///
45/// let mut value = 5;
46/// let mut m = conditional;
47/// m.apply(&mut value);
48/// assert_eq!(value, 10);
49/// ```
50///
51/// # Author
52///
53/// Haixing Hu
54pub struct RcConditionalMutator<T> {
55 pub(super) mutator: RcMutator<T>,
56 pub(super) predicate: RcPredicate<T>,
57}
58
59// Generate shared conditional mutator methods (and_then, or_else)
60impl_shared_conditional_mutator!(
61 RcConditionalMutator<T>,
62 RcMutator,
63 Mutator,
64 into_rc,
65 'static
66);
67
68impl<T> Mutator<T> for RcConditionalMutator<T> {
69 fn apply(&self, value: &mut T) {
70 if self.predicate.test(value) {
71 self.mutator.apply(value);
72 }
73 }
74
75 // Generates: into_box(), into_rc(), into_fn()
76 impl_conditional_mutator_conversions!(BoxMutator<T>, RcMutator, Fn);
77}
78
79// Generate Clone trait implementation for conditional mutator
80impl_conditional_mutator_clone!(RcConditionalMutator<T>);
81
82// Generate Debug and Display trait implementations for conditional mutator
83impl_conditional_mutator_debug_display!(RcConditionalMutator<T>);