qubit_function/functions/mutating_function/arc_conditional_mutating_function.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 `ArcConditionalMutatingFunction` public type.
12
13use super::{
14 ArcMutatingFunction,
15 ArcPredicate,
16 MutatingFunction,
17 Predicate,
18 impl_conditional_function_clone,
19 impl_conditional_function_debug_display,
20 impl_shared_conditional_function,
21};
22
23// ============================================================================
24// ArcConditionalMutatingFunction - Arc-based Conditional Mutating Function
25// ============================================================================
26
27/// ArcConditionalMutatingFunction struct
28///
29/// A thread-safe conditional function that only executes when a predicate is
30/// satisfied. Uses `ArcMutatingFunction` and `ArcPredicate` for shared ownership
31/// across threads.
32///
33/// This type is typically created by calling `ArcMutatingFunction::when()` and is
34/// designed to work with the `or_else()` method to create if-then-else logic.
35///
36/// # Features
37///
38/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
39/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
40/// - **Conditional Execution**: Only transforms when predicate returns `true`
41/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
42///
43/// # Examples
44///
45/// ```rust
46/// use qubit_function::{MutatingFunction, ArcMutatingFunction};
47///
48/// let double = ArcMutatingFunction::new(|x: &mut i32| *x * 2);
49/// let identity = ArcMutatingFunction::<i32, i32>::identity();
50/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
51///
52/// let conditional_clone = conditional.clone();
53///
54/// let mut positive = 5;
55/// assert_eq!(conditional.apply(&mut positive), 10);
56/// let mut negative = -5;
57/// assert_eq!(conditional_clone.apply(&mut negative), -5);
58/// ```
59///
60pub struct ArcConditionalMutatingFunction<T, R> {
61 pub(super) function: ArcMutatingFunction<T, R>,
62 pub(super) predicate: ArcPredicate<T>,
63}
64
65// Use macro to generate conditional function implementations
66impl_shared_conditional_function!(
67 ArcConditionalMutatingFunction<T, R>,
68 ArcMutatingFunction,
69 MutatingFunction,
70 Send + Sync + 'static
71);
72
73// Use macro to generate conditional function clone implementations
74impl_conditional_function_clone!(ArcConditionalMutatingFunction<T, R>);
75
76// Use macro to generate conditional function debug and display implementations
77impl_conditional_function_debug_display!(ArcConditionalMutatingFunction<T, R>);