Skip to main content

qubit_function/transformers/transformer/
arc_conditional_transformer.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the `ArcConditionalTransformer` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// ArcConditionalTransformer - Arc-based Conditional Transformer
17// ============================================================================
18
19/// ArcConditionalTransformer struct
20///
21/// A thread-safe conditional transformer that only executes when a predicate is
22/// satisfied. Uses `ArcTransformer` and `ArcPredicate` for shared ownership
23/// across threads.
24///
25/// This type is typically created by calling `ArcTransformer::when()` and is
26/// designed to work with the `or_else()` method to create if-then-else logic.
27///
28/// # Features
29///
30/// - **Shared Ownership**: Cloneable via `Arc`, multiple owners allowed
31/// - **Thread-Safe**: Implements `Send + Sync`, safe for concurrent use
32/// - **Conditional Execution**: Only transforms when predicate returns `true`
33/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
34///
35/// # Examples
36///
37/// ```rust
38/// use qubit_function::{Transformer, ArcTransformer};
39///
40/// let double = ArcTransformer::new(|x: i32| x * 2);
41/// let identity = ArcTransformer::<i32, i32>::identity();
42/// let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
43///
44/// let conditional_clone = conditional.clone();
45///
46/// assert_eq!(conditional.apply(5), 10);
47/// assert_eq!(conditional_clone.apply(-5), -5);
48/// ```
49///
50/// # Author
51///
52/// Haixing Hu
53pub struct ArcConditionalTransformer<T, R> {
54    pub(super) transformer: ArcTransformer<T, R>,
55    pub(super) predicate: ArcPredicate<T>,
56}
57
58// Implement ArcConditionalTransformer
59impl_shared_conditional_transformer!(
60    ArcConditionalTransformer<T, R>,
61    ArcTransformer,
62    Transformer,
63    into_arc,
64    Send + Sync + 'static
65);
66
67// Use macro to generate Debug and Display implementations
68impl_conditional_transformer_debug_display!(ArcConditionalTransformer<T, R>);
69
70// Implement Clone for ArcConditionalTransformer
71impl_conditional_transformer_clone!(ArcConditionalTransformer<T, R>);