Skip to main content

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