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