Skip to main content

qubit_function/functions/function/
box_conditional_function.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `BoxConditionalFunction` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// BoxConditionalFunction - Box-based Conditional Function
17// ============================================================================
18
19/// BoxConditionalFunction struct
20///
21/// A conditional function that only executes when a predicate is satisfied.
22/// Uses `BoxFunction` and `BoxPredicate` for single ownership semantics.
23///
24/// This type is typically created by calling `BoxFunction::when()` and is
25/// designed to work with the `or_else()` method to create if-then-else logic.
26///
27/// # Features
28///
29/// - **Single Ownership**: Not cloneable, consumes `self` on use
30/// - **Conditional Execution**: Only transforms when predicate returns `true`
31/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
32/// - **Implements Function**: Can be used anywhere a `Function` is expected
33///
34/// # Examples
35///
36/// ## With or_else Branch
37///
38/// ```rust
39/// use qubit_function::{Function, BoxFunction};
40///
41/// let double = BoxFunction::new(|x: &i32| x * 2);
42/// let negate = BoxFunction::new(|x: &i32| -x);
43/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
44///
45/// assert_eq!(conditional.apply(&5), 10); // when branch executed
46/// assert_eq!(conditional.apply(&-5), 5); // or_else branch executed
47/// ```
48///
49/// # Author
50///
51/// Haixing Hu
52pub struct BoxConditionalFunction<T, R> {
53    pub(super) function: BoxFunction<T, R>,
54    pub(super) predicate: BoxPredicate<T>,
55}
56
57// Use macro to generate conditional function implementations
58impl_box_conditional_function!(
59    BoxConditionalFunction<T, R>,
60    BoxFunction,
61    Function
62);
63
64// Use macro to generate conditional function debug and display implementations
65impl_conditional_function_debug_display!(BoxConditionalFunction<T, R>);