Skip to main content

qubit_function/functions/mutating_function/
box_conditional_mutating_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 `BoxConditionalMutatingFunction` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// BoxConditionalMutatingFunction - Box-based Conditional Mutating Function
17// ============================================================================
18
19/// BoxConditionalMutatingFunction struct
20///
21/// A conditional function that only executes when a predicate is satisfied.
22/// Uses `BoxMutatingFunction` and `BoxPredicate` for single ownership semantics.
23///
24/// This type is typically created by calling `BoxMutatingFunction::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::{MutatingFunction, BoxMutatingFunction};
40///
41/// let double = BoxMutatingFunction::new(|x: &mut i32| *x * 2);
42/// let negate = BoxMutatingFunction::new(|x: &mut i32| -*x);
43/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
44///
45/// let mut positive = 5;
46/// assert_eq!(conditional.apply(&mut positive), 10); // when branch executed
47/// let mut negative = -5;
48/// assert_eq!(conditional.apply(&mut negative), 5); // or_else branch executed
49/// ```
50///
51/// # Author
52///
53/// Haixing Hu
54pub struct BoxConditionalMutatingFunction<T, R> {
55    pub(super) function: BoxMutatingFunction<T, R>,
56    pub(super) predicate: BoxPredicate<T>,
57}
58
59// Use macro to generate conditional function implementations
60impl_box_conditional_function!(
61    BoxConditionalMutatingFunction<T, R>,
62    BoxMutatingFunction,
63    MutatingFunction
64);
65
66// Use macro to generate conditional function debug and display implementations
67impl_conditional_function_debug_display!(BoxConditionalMutatingFunction<T, R>);