pub struct ArcTransformer<T, R> { /* private fields */ }Expand description
ArcTransformer - thread-safe transformer wrapper
A thread-safe, clonable transformer wrapper suitable for multi-threaded scenarios. Can be called multiple times and shared across threads.
§Features
- Based on:
Arc<dyn Fn(T) -> R + Send + Sync> - Ownership: Shared ownership via reference counting
- Reusability: Can be called multiple times (each call consumes its input)
- Thread Safety: Thread-safe (
Send + Syncrequired) - Clonable: Cheap cloning via
Arc::clone
§Author
Haixing Hu
Implementations§
Source§impl<T, R> ArcTransformer<T, R>
impl<T, R> ArcTransformer<T, R>
Sourcepub fn new<F>(f: F) -> Self
pub fn new<F>(f: F) -> Self
Creates a new transformer.
Wraps the provided closure in the appropriate smart pointer type for this transformer implementation.
Examples found in repository?
27fn main() {
28 println!("=== TransformerOnce Demo ===\n");
29
30 // BoxTransformer TransformerOnce demonstration
31 println!("1. BoxTransformer TransformerOnce demonstration:");
32 let double = BoxTransformer::new(|x: i32| x * 2);
33 let result = double.apply(21);
34 println!(" double.apply(21) = {}", result);
35
36 // Convert to BoxTransformerOnce
37 let double = BoxTransformer::new(|x: i32| x * 2);
38 let boxed = double.into_box();
39 let result = boxed.apply(21);
40 println!(" double.into_box().apply(21) = {}", result);
41
42 // Convert to function
43 let double = BoxTransformer::new(|x: i32| x * 2);
44 let func = double.into_fn();
45 let result = func(21);
46 println!(" double.into_fn()(21) = {}", result);
47
48 println!();
49
50 // RcTransformer TransformerOnce demonstration
51 println!("2. RcTransformer TransformerOnce demonstration:");
52 let uppercase = RcTransformer::new(|s: String| s.to_uppercase());
53 let result = uppercase.apply("hello".to_string());
54 println!(" uppercase.apply(\"hello\") = {}", result);
55
56 // Use after cloning
57 let uppercase = RcTransformer::new(|s: String| s.to_uppercase());
58 let uppercase_clone = uppercase.clone();
59 let result1 = uppercase.apply("world".to_string());
60 let result2 = uppercase_clone.apply("rust".to_string());
61 println!(" uppercase.apply(\"world\") = {}", result1);
62 println!(" uppercase_clone.apply(\"rust\") = {}", result2);
63
64 println!();
65
66 // ArcTransformer TransformerOnce demonstration
67 println!("3. ArcTransformer TransformerOnce demonstration:");
68 let parse_and_double = ArcTransformer::new(|s: String| s.parse::<i32>().unwrap_or(0) * 2);
69 let result = parse_and_double.apply("21".to_string());
70 println!(" parse_and_double.apply(\"21\") = {}", result);
71
72 // Thread safety demonstration
73 println!("4. ArcTransformer thread safety demonstration:");
74 let double = ArcTransformer::new(|x: i32| x * 2);
75 let double_arc = Arc::new(double);
76 let _double_clone = Arc::clone(&double_arc);
77
78 let handle = thread::spawn(move || {
79 // Create a new transformer in the thread to demonstrate thread safety
80 let new_double = ArcTransformer::new(|x: i32| x * 2);
81 new_double.apply(21)
82 });
83
84 let result = handle.join().unwrap();
85 println!(" Executed in thread: new_double.apply(21) = {}", result);
86
87 println!("\n=== Demo completed ===");
88}More examples
19fn main() {
20 println!("=== Transformer Demo - Type Transformation (consumes T) ===\n");
21
22 // ====================================================================
23 // Part 1: BoxTransformer - Single ownership, reusable
24 // ====================================================================
25 println!("--- BoxTransformer ---");
26 let double = BoxTransformer::new(|x: i32| x * 2);
27 println!("double.apply(21) = {}", double.apply(21));
28 println!("double.apply(42) = {}", double.apply(42));
29
30 // Identity and constant
31 let identity = BoxTransformer::<i32, i32>::identity();
32 println!("identity.apply(42) = {}", identity.apply(42));
33
34 let constant = BoxTransformer::constant("hello");
35 println!("constant.apply(123) = {}", constant.apply(123));
36 println!();
37
38 // ====================================================================
39 // Part 2: ArcTransformer - Thread-safe, cloneable
40 // ====================================================================
41 println!("--- ArcTransformer ---");
42 let arc_double = ArcTransformer::new(|x: i32| x * 2);
43 let arc_cloned = arc_double.clone();
44
45 println!("arc_double.apply(21) = {}", arc_double.apply(21));
46 println!("arc_cloned.apply(42) = {}", arc_cloned.apply(42));
47
48 // Multi-threaded usage
49 let for_thread = arc_double.clone();
50 let handle = thread::spawn(move || for_thread.apply(100));
51 println!(
52 "In main thread: arc_double.apply(50) = {}",
53 arc_double.apply(50)
54 );
55 println!("In child thread: result = {}", handle.join().unwrap());
56 println!();
57
58 // ====================================================================
59 // Part 3: RcTransformer - Single-threaded, cloneable
60 // ====================================================================
61 println!("--- RcTransformer ---");
62 let rc_double = RcTransformer::new(|x: i32| x * 2);
63 let rc_cloned = rc_double.clone();
64
65 println!("rc_double.apply(21) = {}", rc_double.apply(21));
66 println!("rc_cloned.apply(42) = {}", rc_cloned.apply(42));
67 println!();
68
69 // ====================================================================
70 // Part 4: Practical Examples
71 // ====================================================================
72 println!("=== Practical Examples ===\n");
73
74 // Example 1: String transformation
75 println!("--- String Transformation ---");
76 let to_upper = BoxTransformer::new(|s: String| s.to_uppercase());
77 println!(
78 "to_upper.apply('hello') = {}",
79 to_upper.apply("hello".to_string())
80 );
81 println!(
82 "to_upper.apply('world') = {}",
83 to_upper.apply("world".to_string())
84 );
85 println!();
86
87 // Example 2: Type conversion pipeline
88 println!("--- Type Conversion Pipeline ---");
89 let parse_int = BoxTransformer::new(|s: String| s.parse::<i32>().unwrap_or(0));
90 let double_int = BoxTransformer::new(|x: i32| x * 2);
91 let to_string = BoxTransformer::new(|x: i32| x.to_string());
92
93 let pipeline = parse_int.and_then(double_int).and_then(to_string);
94 println!(
95 "pipeline.apply('21') = {}",
96 pipeline.apply("21".to_string())
97 );
98 println!();
99
100 // Example 3: Shared transformation logic
101 println!("--- Shared Transformation Logic ---");
102 let square = ArcTransformer::new(|x: i32| x * x);
103
104 // Can be shared across different parts of the program
105 let transformer1 = square.clone();
106 let transformer2 = square.clone();
107
108 println!("transformer1.apply(5) = {}", transformer1.apply(5));
109 println!("transformer2.apply(7) = {}", transformer2.apply(7));
110 println!("square.apply(3) = {}", square.apply(3));
111 println!();
112
113 // Example 4: Transformer registry
114 println!("--- Transformer Registry ---");
115 let mut transformers: HashMap<String, RcTransformer<i32, String>> = HashMap::new();
116
117 transformers.insert(
118 "double".to_string(),
119 RcTransformer::new(|x: i32| format!("Doubled: {}", x * 2)),
120 );
121 transformers.insert(
122 "square".to_string(),
123 RcTransformer::new(|x: i32| format!("Squared: {}", x * x)),
124 );
125
126 if let Some(transformer) = transformers.get("double") {
127 println!("Transformer 'double': {}", transformer.apply(7));
128 }
129 if let Some(transformer) = transformers.get("square") {
130 println!("Transformer 'square': {}", transformer.apply(7));
131 }
132 println!();
133
134 // ====================================================================
135 // Part 5: Trait Usage
136 // ====================================================================
137 println!("=== Trait Usage ===\n");
138
139 fn apply_transformer<F: Transformer<i32, String>>(f: &F, x: i32) -> String {
140 f.apply(x)
141 }
142
143 let to_string = BoxTransformer::new(|x: i32| format!("Value: {}", x));
144 println!("Via trait: {}", apply_transformer(&to_string, 42));
145
146 println!("\n=== Demo Complete ===");
147}24fn main() {
25 println!("=== TransformerOnce Specialized Methods Demo ===\n");
26
27 // ============================================================================
28 // ArcTransformer TransformerOnce specialized methods
29 // ============================================================================
30
31 println!("1. ArcTransformer TransformerOnce specialized methods:");
32
33 let arc_double = ArcTransformer::new(|x: i32| x * 2);
34
35 // Test into_box - consumes self
36 let boxed_once = arc_double.clone().into_box();
37 println!(" ArcTransformer::into_box(): {}", boxed_once.apply(21));
38
39 // Test into_fn - consumes self
40 let fn_once = arc_double.clone().into_fn();
41 println!(" ArcTransformer::into_fn(): {}", fn_once(21));
42
43 // Test to_box - borrows self
44 let boxed_once_borrowed = arc_double.to_box();
45 println!(
46 " ArcTransformer::to_box(): {}",
47 boxed_once_borrowed.apply(21)
48 );
49
50 // Test to_fn - borrows self
51 let fn_once_borrowed = arc_double.to_fn();
52 println!(" ArcTransformer::to_fn(): {}", fn_once_borrowed(21));
53
54 // Original transformer still usable after to_xxx methods
55 println!(
56 " Original ArcTransformer still works: {}",
57 arc_double.apply(21)
58 );
59
60 println!();
61
62 // ============================================================================
63 // RcTransformer TransformerOnce specialized methods
64 // ============================================================================
65
66 println!("2. RcTransformer TransformerOnce specialized methods:");
67
68 let rc_triple = RcTransformer::new(|x: i32| x * 3);
69
70 // Test into_box - consumes self
71 let boxed_once = rc_triple.clone().into_box();
72 println!(" RcTransformer::into_box(): {}", boxed_once.apply(14));
73
74 // Test into_fn - consumes self
75 let fn_once = rc_triple.clone().into_fn();
76 println!(" RcTransformer::into_fn(): {}", fn_once(14));
77
78 // Test to_box - borrows self
79 let boxed_once_borrowed = rc_triple.to_box();
80 println!(
81 " RcTransformer::to_box(): {}",
82 boxed_once_borrowed.apply(14)
83 );
84
85 // Test to_fn - borrows self
86 let fn_once_borrowed = rc_triple.to_fn();
87 println!(" RcTransformer::to_fn(): {}", fn_once_borrowed(14));
88
89 // Original transformer still usable after to_xxx methods
90 println!(
91 " Original RcTransformer still works: {}",
92 rc_triple.apply(14)
93 );
94
95 println!();
96
97 // ============================================================================
98 // Comparison with default implementations
99 // ============================================================================
100
101 println!("3. Performance comparison (specialized vs default):");
102
103 let arc_square = ArcTransformer::new(|x: i32| x * x);
104
105 // Using specialized method (more efficient)
106 let specialized_box = arc_square.clone().into_box();
107 println!(" Specialized into_box: {}", specialized_box.apply(5));
108
109 // Using default implementation (less efficient)
110 let default_box = arc_square.clone().into_box();
111 println!(" Default into_box: {}", default_box.apply(5));
112
113 println!();
114
115 // ============================================================================
116 // Thread safety demonstration for ArcTransformer
117 // ============================================================================
118
119 println!("4. Thread safety with ArcTransformer:");
120
121 let arc_shared = ArcTransformer::new(|x: i32| x + 100);
122
123 // Clone for thread safety
124 let arc_clone = arc_shared.clone();
125
126 // Use in different thread context (simulated)
127 let handle = std::thread::spawn(move || {
128 let boxed = arc_clone.into_box();
129 boxed.apply(50)
130 });
131
132 let result = handle.join().unwrap();
133 println!(" Thread-safe ArcTransformer result: {}", result);
134
135 // Original still usable
136 println!(
137 " Original ArcTransformer still works: {}",
138 arc_shared.apply(50)
139 );
140
141 println!();
142
143 // ============================================================================
144 // String transformation example
145 // ============================================================================
146
147 println!("5. String transformation with specialized methods:");
148
149 let arc_uppercase = ArcTransformer::new(|s: String| s.to_uppercase());
150
151 // Test with string input
152 let test_string = "hello world".to_string();
153
154 // Using specialized methods
155 let boxed_upper = arc_uppercase.clone().into_box();
156 let result = boxed_upper.apply(test_string.clone());
157 println!(
158 " String transformation: '{}' -> '{}'",
159 test_string, result
160 );
161
162 // Using to_xxx methods (borrowing)
163 let fn_upper = arc_uppercase.to_fn();
164 let result2 = fn_upper(test_string.clone());
165 println!(
166 " String transformation (borrowed): '{}' -> '{}'",
167 test_string, result2
168 );
169
170 // Original still usable
171 println!(
172 " Original ArcTransformer still works: '{}'",
173 arc_uppercase.apply(test_string)
174 );
175
176 println!("\n=== Demo completed successfully! ===");
177}Sourcepub fn new_with_name<F>(name: &str, f: F) -> Self
pub fn new_with_name<F>(name: &str, f: F) -> Self
Creates a new named transformer.
Wraps the provided closure and assigns it a name, which is useful for debugging and logging purposes.
Sourcepub fn new_with_optional_name<F>(f: F, name: Option<String>) -> Self
pub fn new_with_optional_name<F>(f: F, name: Option<String>) -> Self
Creates a new named transformer with an optional name.
Wraps the provided closure and assigns it an optional name.
Sourcepub fn clear_name(&mut self)
pub fn clear_name(&mut self)
Clears the name of this transformer.
Sourcepub fn identity() -> ArcTransformer<T, T>
pub fn identity() -> ArcTransformer<T, T>
Creates an identity transformer.
Creates a transformer that returns the input value unchanged. Useful for default values or placeholder implementations.
§Returns
Returns a new transformer instance that returns the input unchanged.
pub fn when<P>(&self, predicate: P) -> ArcConditionalTransformer<T, R>
pub fn and_then<S, F>(&self, after: F) -> ArcTransformer<T, S>
Source§impl<T, R> ArcTransformer<T, R>
impl<T, R> ArcTransformer<T, R>
Sourcepub fn constant(value: R) -> ArcTransformer<T, R>
pub fn constant(value: R) -> ArcTransformer<T, R>
Creates a constant transformer
§Examples
/// rust /// use qubit_function::{ArcTransformer, Transformer}; /// /// let constant = ArcTransformer::constant("hello"); /// assert_eq!(constant.apply(123), "hello"); ///
Trait Implementations§
Source§impl<T, R> Clone for ArcTransformer<T, R>
impl<T, R> Clone for ArcTransformer<T, R>
Source§impl<T, R> Debug for ArcTransformer<T, R>
impl<T, R> Debug for ArcTransformer<T, R>
Source§impl<T, R> Display for ArcTransformer<T, R>
impl<T, R> Display for ArcTransformer<T, R>
Source§impl<T, R> Transformer<T, R> for ArcTransformer<T, R>
impl<T, R> Transformer<T, R> for ArcTransformer<T, R>
Source§fn apply(&self, input: T) -> R
fn apply(&self, input: T) -> R
Source§fn into_box(self) -> BoxTransformer<T, R>where
Self: 'static,
fn into_box(self) -> BoxTransformer<T, R>where
Self: 'static,
Source§fn into_rc(self) -> RcTransformer<T, R>where
Self: 'static,
fn into_rc(self) -> RcTransformer<T, R>where
Self: 'static,
Source§fn into_arc(self) -> ArcTransformer<T, R>
fn into_arc(self) -> ArcTransformer<T, R>
Source§fn into_once(self) -> BoxTransformerOnce<T, R>where
Self: 'static,
fn into_once(self) -> BoxTransformerOnce<T, R>where
Self: 'static,
BoxTransformerOnce. Read moreSource§fn to_box(&self) -> BoxTransformer<T, R>where
Self: 'static,
fn to_box(&self) -> BoxTransformer<T, R>where
Self: 'static,
Source§fn to_rc(&self) -> RcTransformer<T, R>where
Self: 'static,
fn to_rc(&self) -> RcTransformer<T, R>where
Self: 'static,
Source§fn to_arc(&self) -> ArcTransformer<T, R>
fn to_arc(&self) -> ArcTransformer<T, R>
Source§fn to_fn(&self) -> impl Fn(T) -> R
fn to_fn(&self) -> impl Fn(T) -> R
Source§fn to_once(&self) -> BoxTransformerOnce<T, R>where
Self: 'static,
fn to_once(&self) -> BoxTransformerOnce<T, R>where
Self: 'static,
BoxTransformerOnce without consuming self Read more