Skip to main content

qubit_function/transformers/transformer/
arc_conditional_transformer.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 `ArcConditionalTransformer` public type.
12
13use super::{
14    ArcPredicate,
15    ArcTransformer,
16    Predicate,
17    Transformer,
18    impl_conditional_transformer_clone,
19    impl_conditional_transformer_debug_display,
20    impl_shared_conditional_transformer,
21};
22
23// ============================================================================
24// ArcConditionalTransformer - Arc-based Conditional Transformer
25// ============================================================================
26
27/// ArcConditionalTransformer struct
28///
29/// A thread-safe conditional transformer that only executes when a predicate is
30/// satisfied. Uses `ArcTransformer` and `ArcPredicate` for shared ownership
31/// across threads.
32///
33/// This type is typically created by calling `ArcTransformer::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::{Transformer, ArcTransformer};
47///
48/// let double = ArcTransformer::new(|x: i32| x * 2);
49/// let identity = ArcTransformer::<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 ArcConditionalTransformer<T, R> {
59    pub(super) transformer: ArcTransformer<T, R>,
60    pub(super) predicate: ArcPredicate<T>,
61}
62
63// Implement ArcConditionalTransformer
64impl_shared_conditional_transformer!(
65    ArcConditionalTransformer<T, R>,
66    ArcTransformer,
67    Transformer,
68    into_arc,
69    Send + Sync + 'static
70);
71
72// Use macro to generate Debug and Display implementations
73impl_conditional_transformer_debug_display!(ArcConditionalTransformer<T, R>);
74
75// Implement Clone for ArcConditionalTransformer
76impl_conditional_transformer_clone!(ArcConditionalTransformer<T, R>);