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