Skip to main content

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