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