Skip to main content

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