Skip to main content

qubit_function/functions/bi_function/
rc_conditional_bi_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 `RcConditionalBiFunction` public type.
12
13use super::{
14    BiFunction,
15    BiPredicate,
16    RcBiFunction,
17    RcBiPredicate,
18    impl_conditional_function_clone,
19    impl_conditional_function_debug_display,
20    impl_shared_conditional_function,
21};
22
23// ============================================================================
24// RcConditionalBiFunction - Rc-based Conditional BiFunction
25// ============================================================================
26
27/// RcConditionalBiFunction struct
28///
29/// A single-threaded conditional bi-function that only executes when a
30/// bi-predicate is satisfied. Uses `RcBiFunction` and `RcBiPredicate` for
31/// shared ownership within a single thread.
32///
33/// This type is typically created by calling `RcBiFunction::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 computes when bi-predicate returns `true`
41/// - **No Lock Overhead**: More efficient than `ArcConditionalBiFunction`
42///
43/// # Examples
44///
45/// ```rust
46/// use qubit_function::{BiFunction, RcBiFunction};
47///
48/// let add = RcBiFunction::new(|x: &i32, y: &i32| *x + *y);
49/// let multiply = RcBiFunction::new(|x: &i32, y: &i32| *x * *y);
50/// let conditional = add.when(|x: &i32, y: &i32| *x > 0).or_else(multiply);
51///
52/// let conditional_clone = conditional.clone();
53///
54/// assert_eq!(conditional.apply(&5, &3), 8);
55/// assert_eq!(conditional_clone.apply(&-5, &3), -15);
56/// ```
57///
58pub struct RcConditionalBiFunction<T, U, R> {
59    pub(super) function: RcBiFunction<T, U, R>,
60    pub(super) predicate: RcBiPredicate<T, U>,
61}
62
63// Implement RcConditionalBiFunction
64impl_shared_conditional_function!(
65    RcConditionalBiFunction<T, U, R>,
66    RcBiFunction,
67    BiFunction,
68    into_rc,
69    'static
70);
71
72// Use macro to generate Debug and Display implementations
73impl_conditional_function_debug_display!(RcConditionalBiFunction<T, U, R>);
74
75// Implement Clone for RcConditionalBiFunction
76impl_conditional_function_clone!(RcConditionalBiFunction<T, U, R>);