Skip to main content

qubit_function/functions/bi_function/
arc_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 `ArcConditionalBiFunction` public type.
12
13use super::{
14    ArcBiFunction,
15    ArcBiPredicate,
16    BiFunction,
17    BiPredicate,
18    impl_conditional_function_clone,
19    impl_conditional_function_debug_display,
20    impl_shared_conditional_function,
21};
22
23// ============================================================================
24// ArcConditionalBiFunction - Arc-based Conditional BiFunction
25// ============================================================================
26
27/// ArcConditionalBiFunction struct
28///
29/// A thread-safe conditional bi-function that only executes when a
30/// bi-predicate is satisfied. Uses `ArcBiFunction` and `ArcBiPredicate` for
31/// shared ownership across threads.
32///
33/// This type is typically created by calling `ArcBiFunction::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 `Arc`, multiple owners allowed
39/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
40/// - **Conditional Execution**: Only computes when bi-predicate returns `true`
41/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
42///
43/// # Examples
44///
45/// ```rust
46/// use qubit_function::{BiFunction, ArcBiFunction};
47///
48/// let add = ArcBiFunction::new(|x: &i32, y: &i32| *x + *y);
49/// let multiply = ArcBiFunction::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 ArcConditionalBiFunction<T, U, R> {
59    pub(super) function: ArcBiFunction<T, U, R>,
60    pub(super) predicate: ArcBiPredicate<T, U>,
61}
62
63// Implement ArcConditionalBiFunction
64impl_shared_conditional_function!(
65    ArcConditionalBiFunction<T, U, R>,
66    ArcBiFunction,
67    BiFunction,
68    into_arc,
69    Send + Sync + 'static
70);
71
72// Implement Debug and Display for ArcConditionalBiFunction
73impl_conditional_function_debug_display!(ArcConditionalBiFunction<T, U, R>);
74
75// Implement Clone for ArcConditionalBiFunction
76impl_conditional_function_clone!(ArcConditionalBiFunction<T, U, R>);