qubit_function/transformers/stateful_transformer/rc_stateful_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 `RcStatefulTransformer` public type.
10
11#![allow(unused_imports)]
12
13use super::*;
14
15// ============================================================================
16// RcStatefulTransformer - Rc<RefCell<dyn FnMut(T) -> R>>
17// ============================================================================
18
19/// RcStatefulTransformer - single-threaded transformer wrapper
20///
21/// A single-threaded, clonable transformer wrapper optimized for scenarios
22/// that require sharing without thread-safety overhead.
23///
24/// # Features
25///
26/// - **Based on**: `Rc<RefCell<dyn FnMut(T) -> R>>`
27/// - **Ownership**: Shared ownership via reference counting (non-atomic)
28/// - **Reusability**: Can be called multiple times (each call consumes
29/// its input)
30/// - **Thread Safety**: Not thread-safe (no `Send + Sync`)
31/// - **Clonable**: Cheap cloning via `Rc::clone`
32/// - **Statefulness**: Can modify internal state between calls
33///
34/// # Author
35///
36/// Haixing Hu
37pub struct RcStatefulTransformer<T, R> {
38 pub(super) function: Rc<RefCell<dyn FnMut(T) -> R>>,
39 pub(super) name: Option<String>,
40}
41
42// Implement RcStatefulTransformer
43impl<T, R> RcStatefulTransformer<T, R> {
44 impl_transformer_common_methods!(
45 RcStatefulTransformer<T, R>,
46 (FnMut(T) -> R + 'static),
47 |f| Rc::new(RefCell::new(f))
48 );
49
50 impl_shared_transformer_methods!(
51 RcStatefulTransformer<T, R>,
52 RcConditionalStatefulTransformer,
53 into_rc,
54 StatefulTransformer,
55 'static
56 );
57}
58
59// Implement constant method for RcStatefulTransformer
60impl_transformer_constant_method!(stateful RcStatefulTransformer<T, R>);
61
62// Implement Debug and Display for RcStatefulTransformer
63impl_transformer_debug_display!(RcStatefulTransformer<T, R>);
64
65// Implement Clone for RcStatefulTransformer
66impl_transformer_clone!(RcStatefulTransformer<T, R>);
67
68// Implement StatefulTransformer trait for RcStatefulTransformer
69impl<T, R> StatefulTransformer<T, R> for RcStatefulTransformer<T, R> {
70 fn apply(&mut self, input: T) -> R {
71 let mut self_fn = self.function.borrow_mut();
72 self_fn(input)
73 }
74
75 // Generate all conversion methods using the unified macro
76 impl_rc_conversions!(
77 RcStatefulTransformer<T, R>,
78 BoxStatefulTransformer,
79 BoxTransformerOnce,
80 FnMut(input: T) -> R
81 );
82}