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