qubit_function/transformers/transformer/rc_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 `RcConditionalTransformer` public type.
12
13use super::{
14 Predicate,
15 RcPredicate,
16 RcTransformer,
17 Transformer,
18 impl_conditional_transformer_clone,
19 impl_conditional_transformer_debug_display,
20 impl_shared_conditional_transformer,
21};
22
23// ============================================================================
24// RcConditionalTransformer - Rc-based Conditional Transformer
25// ============================================================================
26
27/// RcConditionalTransformer struct
28///
29/// A single-threaded conditional transformer that only executes when a
30/// predicate is satisfied. Uses `RcTransformer` and `RcPredicate` for shared
31/// ownership within a single thread.
32///
33/// This type is typically created by calling `RcTransformer::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 `Rc`, multiple owners allowed
39/// - **Single-Threaded**: Not thread-safe, cannot be sent across threads
40/// - **Conditional Execution**: Only transforms when predicate returns `true`
41/// - **No Lock Overhead**: More efficient than `ArcConditionalTransformer`
42///
43/// # Examples
44///
45/// ```rust
46/// use qubit_function::{Transformer, RcTransformer};
47///
48/// let double = RcTransformer::new(|x: i32| x * 2);
49/// let identity = RcTransformer::<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 RcConditionalTransformer<T, R> {
59 pub(super) transformer: RcTransformer<T, R>,
60 pub(super) predicate: RcPredicate<T>,
61}
62
63// Implement RcConditionalTransformer
64impl_shared_conditional_transformer!(
65 RcConditionalTransformer<T, R>,
66 RcTransformer,
67 Transformer,
68 into_rc,
69 'static
70);
71
72// Use macro to generate Debug and Display implementations
73impl_conditional_transformer_debug_display!(RcConditionalTransformer<T, R>);
74
75// Implement Clone for RcConditionalTransformer
76impl_conditional_transformer_clone!(RcConditionalTransformer<T, R>);