Skip to main content

qubit_function/mutators/mutator/
arc_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 `ArcConditionalMutator` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// 10. ArcConditionalMutator - Arc-based Conditional Mutator
17// ============================================================================
18
19/// ArcConditionalMutator struct
20///
21/// A thread-safe conditional mutator that only executes when a predicate is
22/// satisfied. Uses `ArcMutator` and `ArcPredicate` for shared ownership across
23/// threads.
24///
25/// This type is typically created by calling `ArcMutator::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 `Arc`, multiple owners allowed
31/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
32/// - **Conditional Execution**: Only mutates when predicate returns `true`
33/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
34///
35/// # Examples
36///
37/// ```rust
38/// use qubit_function::{Mutator, ArcMutator};
39///
40/// let conditional = ArcMutator::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 ArcConditionalMutator<T> {
55    pub(super) mutator: ArcMutator<T>,
56    pub(super) predicate: ArcPredicate<T>,
57}
58
59// Generate shared conditional mutator methods (and_then, or_else, conversions)
60impl_shared_conditional_mutator!(
61    ArcConditionalMutator<T>,
62    ArcMutator,
63    Mutator,
64    into_arc,
65    Send + Sync + 'static
66);
67
68impl<T> Mutator<T> for ArcConditionalMutator<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!(ArcConditionalMutator<T>);
81
82// Generate Debug and Display trait implementations for conditional mutator
83impl_conditional_mutator_debug_display!(ArcConditionalMutator<T>);