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