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