Skip to main content

qubit_function/functions/mutating_function/
rc_conditional_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 `RcConditionalMutatingFunction` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// RcConditionalMutatingFunction - Rc-based Conditional Mutating Function
17// ============================================================================
18
19/// RcConditionalMutatingFunction struct
20///
21/// A single-threaded conditional function that only executes when a
22/// predicate is satisfied. Uses `RcMutatingFunction` and `RcPredicate` for shared
23/// ownership within a single thread.
24///
25/// This type is typically created by calling `RcMutatingFunction::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 `Rc`, multiple owners allowed
31/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
32/// - **Conditional Execution**: Only transforms when predicate returns `true`
33/// - **No Lock Overhead**: More efficient than `ArcConditionalFunction`
34///
35/// # Examples
36///
37/// ```rust
38/// use qubit_function::{MutatingFunction, RcMutatingFunction};
39///
40/// let double = RcMutatingFunction::new(|x: &mut i32| *x * 2);
41/// let identity = RcMutatingFunction::<i32, i32>::identity();
42/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
43///
44/// let conditional_clone = conditional.clone();
45///
46/// let mut positive = 5;
47/// assert_eq!(conditional.apply(&mut positive), 10);
48/// let mut negative = -5;
49/// assert_eq!(conditional_clone.apply(&mut negative), -5);
50/// ```
51///
52/// # Author
53///
54/// Haixing Hu
55pub struct RcConditionalMutatingFunction<T, R> {
56    pub(super) function: RcMutatingFunction<T, R>,
57    pub(super) predicate: RcPredicate<T>,
58}
59
60// Use macro to generate conditional function implementations
61impl_shared_conditional_function!(
62    RcConditionalMutatingFunction<T, R>,
63    RcMutatingFunction,
64    MutatingFunction,
65    'static
66);
67
68// Use macro to generate conditional function clone implementations
69impl_conditional_function_clone!(RcConditionalMutatingFunction<T, R>);
70
71// Use macro to generate conditional function debug and display implementations
72impl_conditional_function_debug_display!(RcConditionalMutatingFunction<T, R>);