Skip to main content

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