Skip to main content

qubit_function/functions/bi_function/
box_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 `BoxConditionalBiFunction` public type.
12
13use super::{
14    BiFunction,
15    BiPredicate,
16    BoxBiFunction,
17    BoxBiPredicate,
18    impl_box_conditional_function,
19    impl_conditional_function_debug_display,
20};
21
22// ============================================================================
23// BoxConditionalBiFunction - Box-based Conditional BiFunction
24// ============================================================================
25
26/// BoxConditionalBiFunction struct
27///
28/// A conditional bi-function that only executes when a bi-predicate is
29/// satisfied. Uses `BoxBiFunction` and `BoxBiPredicate` for single
30/// ownership semantics.
31///
32/// This type is typically created by calling `BoxBiFunction::when()` and is
33/// designed to work with the `or_else()` method to create if-then-else logic.
34///
35/// # Features
36///
37/// - **Single Ownership**: Not cloneable, consumes `self` on use
38/// - **Conditional Execution**: Only computes when bi-predicate returns `true`
39/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
40/// - **Implements BiFunction**: Can be used anywhere a `BiFunction` is expected
41///
42/// # Examples
43///
44/// ## With or_else Branch
45///
46/// ```rust
47/// use qubit_function::{BiFunction, BoxBiFunction};
48///
49/// let add = BoxBiFunction::new(|x: &i32, y: &i32| *x + *y);
50/// let multiply = BoxBiFunction::new(|x: &i32, y: &i32| *x * *y);
51/// let conditional = add.when(|x: &i32, y: &i32| *x > 0).or_else(multiply);
52///
53/// assert_eq!(conditional.apply(&5, &3), 8);  // when branch executed
54/// assert_eq!(conditional.apply(&-5, &3), -15); // or_else branch executed
55/// ```
56///
57pub struct BoxConditionalBiFunction<T, U, R> {
58    pub(super) function: BoxBiFunction<T, U, R>,
59    pub(super) predicate: BoxBiPredicate<T, U>,
60}
61
62// Implement BoxConditionalBiFunction
63impl_box_conditional_function!(
64    BoxConditionalBiFunction<T, U, R>,
65    BoxBiFunction,
66    BiFunction
67);
68
69// Use macro to generate Debug and Display implementations
70impl_conditional_function_debug_display!(BoxConditionalBiFunction<T, U, R>);