qubit_function/functions/stateful_function/arc_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 `ArcConditionalStatefulFunction` public type.
12
13use super::{
14 ArcPredicate,
15 ArcStatefulFunction,
16 Predicate,
17 StatefulFunction,
18 impl_conditional_function_clone,
19 impl_conditional_function_debug_display,
20 impl_shared_conditional_function,
21};
22
23// ============================================================================
24// ArcConditionalStatefulFunction - Arc-based Conditional StatefulFunction
25// ============================================================================
26
27/// ArcConditionalStatefulFunction struct
28///
29/// A thread-safe conditional function that only executes when a predicate
30/// is satisfied. Uses `ArcStatefulFunction` and `ArcPredicate` for shared
31/// ownership across threads.
32///
33/// This type is typically created by calling `ArcStatefulFunction::when()` and is
34/// designed to work with the `or_else()` method to create if-then-else
35/// logic.
36///
37/// # Features
38///
39/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
40/// - **Thread-Safe**: Implements `Send`, safe for concurrent use
41/// - **Conditional Execution**: Only maps when predicate returns `true`
42/// - **Chainable**: Can add `or_else` branch to create if-then-else
43/// logic
44///
45/// # Examples
46///
47/// ```rust
48/// use qubit_function::{StatefulFunction, ArcStatefulFunction};
49///
50/// let mut function = ArcStatefulFunction::new(|x: &i32| x * 2)
51/// .when(|x: &i32| *x > 0)
52/// .or_else(|x: &i32| -x);
53///
54/// let mut function_clone = function.clone();
55///
56/// assert_eq!(function.apply(&5), 10);
57/// assert_eq!(function_clone.apply(&-5), 5);
58/// ```
59///
60pub struct ArcConditionalStatefulFunction<T, R> {
61 pub(super) function: ArcStatefulFunction<T, R>,
62 pub(super) predicate: ArcPredicate<T>,
63}
64
65// Use macro to generate conditional function implementations
66impl_shared_conditional_function!(
67 ArcConditionalStatefulFunction<T, R>,
68 ArcStatefulFunction,
69 StatefulFunction,
70 Send + Sync + 'static
71);
72
73// Use macro to generate conditional function clone implementations
74impl_conditional_function_clone!(ArcConditionalStatefulFunction<T, R>);
75
76// Use macro to generate conditional function debug and display implementations
77impl_conditional_function_debug_display!(ArcConditionalStatefulFunction<T, R>);