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