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