Skip to main content

qubit_function/functions/stateful_function/
box_conditional_stateful_function.rs

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