Skip to main content

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