Skip to main content

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