qubit_function/transformers/transformer/arc_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 `ArcTransformer` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// ArcTransformer - Arc<dyn Fn(T) -> R + Send + Sync>
17// ============================================================================
18
19/// ArcTransformer - thread-safe transformer wrapper
20///
21/// A thread-safe, clonable transformer wrapper suitable for multi-threaded
22/// scenarios. Can be called multiple times and shared across threads.
23///
24/// # Features
25///
26/// - **Based on**: `Arc<dyn Fn(T) -> R + Send + Sync>`
27/// - **Ownership**: Shared ownership via reference counting
28/// - **Reusability**: Can be called multiple times (each call consumes its
29/// input)
30/// - **Thread Safety**: Thread-safe (`Send + Sync` required)
31/// - **Clonable**: Cheap cloning via `Arc::clone`
32///
33/// # Author
34///
35/// Haixing Hu
36pub struct ArcTransformer<T, R> {
37 pub(super) function: Arc<dyn Fn(T) -> R + Send + Sync>,
38 pub(super) name: Option<String>,
39}
40
41// Implement ArcTransformer
42impl<T, R> ArcTransformer<T, R> {
43 impl_transformer_common_methods!(
44 ArcTransformer<T, R>,
45 (Fn(T) -> R + Send + Sync + 'static),
46 |f| Arc::new(f)
47 );
48
49 impl_shared_transformer_methods!(
50 ArcTransformer<T, R>,
51 ArcConditionalTransformer,
52 into_arc,
53 Transformer,
54 Send + Sync + 'static
55 );
56}
57
58// Implement constant method for ArcTransformer
59impl_transformer_constant_method!(thread_safe ArcTransformer<T, R>);
60
61// Implement Debug and Display for ArcTransformer
62impl_transformer_debug_display!(ArcTransformer<T, R>);
63
64// Implement Clone for ArcTransformer
65impl_transformer_clone!(ArcTransformer<T, R>);
66
67// Implement Transformer for ArcTransformer
68impl<T, R> Transformer<T, R> for ArcTransformer<T, R> {
69 fn apply(&self, input: T) -> R {
70 (self.function)(input)
71 }
72
73 // Use macro to implement conversion methods
74 impl_arc_conversions!(
75 ArcTransformer<T, R>,
76 BoxTransformer,
77 RcTransformer,
78 BoxTransformerOnce,
79 Fn(t: T) -> R
80 );
81}
82
83// ============================================================================
84// Blanket implementation for standard Fn trait
85// ============================================================================
86
87// Implement Transformer<T, R> for any type that implements Fn(T) -> R
88impl_closure_trait!(
89 Transformer<T, R>,
90 apply,
91 BoxTransformerOnce,
92 Fn(input: T) -> R
93);