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