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