Skip to main content

qubit_function/functions/function_once/
box_conditional_function_once.rs

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