qubit_function/functions/stateful_mutating_function/box_conditional_stateful_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 `BoxConditionalStatefulMutatingFunction` public type.
12
13use super::{
14 BoxPredicate,
15 BoxStatefulMutatingFunction,
16 Predicate,
17 StatefulMutatingFunction,
18 impl_box_conditional_function,
19 impl_conditional_function_debug_display,
20};
21
22// ============================================================================
23// BoxConditionalStatefulMutatingFunction - Box-based Conditional Stateful Mutating Function
24// ============================================================================
25
26/// BoxConditionalStatefulMutatingFunction struct
27///
28/// A conditional function that only executes when a predicate is satisfied.
29/// Uses `BoxStatefulMutatingFunction` and `BoxPredicate` for single ownership semantics.
30///
31/// This type is typically created by calling `BoxStatefulMutatingFunction::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::{StatefulMutatingFunction, BoxStatefulMutatingFunction};
47///
48/// let double = BoxStatefulMutatingFunction::new(|x: &mut i32| {
49/// *x *= 2;
50/// *x
51/// });
52/// let negate = BoxStatefulMutatingFunction::new(|x: &mut i32| {
53/// *x = -*x;
54/// *x
55/// });
56/// let mut conditional = double.when(|x: &i32| *x > 0).or_else(negate);
57///
58/// let mut positive = 5;
59/// let mut negative = -5;
60/// assert_eq!(conditional.apply(&mut positive), 10); // when branch executed
61/// assert_eq!(conditional.apply(&mut negative), 5); // or_else branch executed
62/// ```
63///
64pub struct BoxConditionalStatefulMutatingFunction<T, R> {
65 pub(super) function: BoxStatefulMutatingFunction<T, R>,
66 pub(super) predicate: BoxPredicate<T>,
67}
68
69// Use macro to generate conditional function implementations
70impl_box_conditional_function!(
71 BoxConditionalStatefulMutatingFunction<T, R>,
72 BoxStatefulMutatingFunction,
73 StatefulMutatingFunction
74);
75
76// Use macro to generate conditional function debug and display implementations
77impl_conditional_function_debug_display!(BoxConditionalStatefulMutatingFunction<T, R>);