Skip to main content

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