Skip to main content

qubit_function/functions/stateful_mutating_function/
arc_conditional_stateful_mutating_function.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `ArcConditionalStatefulMutatingFunction` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// ArcConditionalStatefulMutatingFunction - Arc-based Conditional Stateful Mutating Function
17// ============================================================================
18
19/// ArcConditionalStatefulMutatingFunction struct
20///
21/// A thread-safe conditional function that only executes when a predicate is
22/// satisfied. Uses `ArcStatefulMutatingFunction` and `ArcPredicate` for shared ownership
23/// across threads.
24///
25/// This type is typically created by calling `ArcStatefulMutatingFunction::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 transforms 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::{StatefulMutatingFunction, ArcStatefulMutatingFunction};
39///
40/// let double = ArcStatefulMutatingFunction::new(|x: &mut i32| {
41///     *x *= 2;
42///     *x
43/// });
44/// let identity = ArcStatefulMutatingFunction::<i32, i32>::identity();
45/// let mut conditional = double.when(|x: &i32| *x > 0).or_else(identity);
46///
47/// let mut conditional_clone = conditional.clone();
48///
49/// let mut positive = 5;
50/// let mut negative = -5;
51/// assert_eq!(conditional.apply(&mut positive), 10);
52/// assert_eq!(conditional_clone.apply(&mut negative), -5);
53/// ```
54///
55/// # Author
56///
57/// Haixing Hu
58pub struct ArcConditionalStatefulMutatingFunction<T, R> {
59    pub(super) function: ArcStatefulMutatingFunction<T, R>,
60    pub(super) predicate: ArcPredicate<T>,
61}
62
63// Use macro to generate conditional function implementations
64impl_shared_conditional_function!(
65    ArcConditionalStatefulMutatingFunction<T, R>,
66    ArcStatefulMutatingFunction,
67    StatefulMutatingFunction,
68    Send + Sync + 'static
69);
70
71// Use macro to generate conditional function clone implementations
72impl_conditional_function_clone!(ArcConditionalStatefulMutatingFunction<T, R>);
73
74// Use macro to generate conditional function debug and display implementations
75impl_conditional_function_debug_display!(ArcConditionalStatefulMutatingFunction<T, R>);