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
§Author
Hu Haixing
Implementations§
Source§impl<T, R> RcTransformer<T, R>where
T: 'static,
R: 'static,
impl<T, R> RcTransformer<T, R>where
T: 'static,
R: 'static,
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 RcTransformer
§Parameters
f- The closure or function to wrap
§Examples
use prism3_function::{RcTransformer, Transformer};
let double = RcTransformer::new(|x: i32| x * 2);
assert_eq!(double.apply(21), 42);Examples found in repository?
22fn main() {
23 println!("=== TransformerOnce Demo ===\n");
24
25 // BoxTransformer TransformerOnce demonstration
26 println!("1. BoxTransformer TransformerOnce demonstration:");
27 let double = BoxTransformer::new(|x: i32| x * 2);
28 let result = double.apply_once(21);
29 println!(" double.apply_once(21) = {}", result);
30
31 // Convert to BoxTransformerOnce
32 let double = BoxTransformer::new(|x: i32| x * 2);
33 let boxed = double.into_box_once();
34 let result = boxed.apply_once(21);
35 println!(" double.into_box_once().apply_once(21) = {}", result);
36
37 // Convert to function
38 let double = BoxTransformer::new(|x: i32| x * 2);
39 let func = double.into_fn_once();
40 let result = func(21);
41 println!(" double.into_fn_once()(21) = {}", result);
42
43 println!();
44
45 // RcTransformer TransformerOnce demonstration
46 println!("2. RcTransformer TransformerOnce demonstration:");
47 let uppercase = RcTransformer::new(|s: String| s.to_uppercase());
48 let result = uppercase.apply_once("hello".to_string());
49 println!(" uppercase.apply_once(\"hello\") = {}", result);
50
51 // Use after cloning
52 let uppercase = RcTransformer::new(|s: String| s.to_uppercase());
53 let uppercase_clone = uppercase.clone();
54 let result1 = uppercase.apply_once("world".to_string());
55 let result2 = uppercase_clone.apply_once("rust".to_string());
56 println!(" uppercase.apply_once(\"world\") = {}", result1);
57 println!(" uppercase_clone.apply_once(\"rust\") = {}", result2);
58
59 println!();
60
61 // ArcTransformer TransformerOnce demonstration
62 println!("3. ArcTransformer TransformerOnce demonstration:");
63 let parse_and_double = ArcTransformer::new(|s: String| s.parse::<i32>().unwrap_or(0) * 2);
64 let result = parse_and_double.apply_once("21".to_string());
65 println!(" parse_and_double.apply_once(\"21\") = {}", result);
66
67 // Thread safety demonstration
68 println!("4. ArcTransformer thread safety demonstration:");
69 let double = ArcTransformer::new(|x: i32| x * 2);
70 let double_arc = Arc::new(double);
71 let _double_clone = Arc::clone(&double_arc);
72
73 let handle = thread::spawn(move || {
74 // Create a new transformer in the thread to demonstrate thread safety
75 let new_double = ArcTransformer::new(|x: i32| x * 2);
76 new_double.apply_once(21)
77 });
78
79 let result = handle.join().unwrap();
80 println!(
81 " Executed in thread: new_double.apply_once(21) = {}",
82 result
83 );
84
85 println!("\n=== Demo completed ===");
86}More examples
14fn main() {
15 println!("=== Transformer Demo - Type Transformation (consumes T) ===\n");
16
17 // ====================================================================
18 // Part 1: BoxTransformer - Single ownership, reusable
19 // ====================================================================
20 println!("--- BoxTransformer ---");
21 let double = BoxTransformer::new(|x: i32| x * 2);
22 println!("double.apply(21) = {}", double.apply(21));
23 println!("double.apply(42) = {}", double.apply(42));
24
25 // Identity and constant
26 let identity = BoxTransformer::<i32, i32>::identity();
27 println!("identity.apply(42) = {}", identity.apply(42));
28
29 let constant = BoxTransformer::constant("hello");
30 println!("constant.apply(123) = {}", constant.apply(123));
31 println!();
32
33 // ====================================================================
34 // Part 2: ArcTransformer - Thread-safe, cloneable
35 // ====================================================================
36 println!("--- ArcTransformer ---");
37 let arc_double = ArcTransformer::new(|x: i32| x * 2);
38 let arc_cloned = arc_double.clone();
39
40 println!("arc_double.apply(21) = {}", arc_double.apply(21));
41 println!("arc_cloned.apply(42) = {}", arc_cloned.apply(42));
42
43 // Multi-threaded usage
44 let for_thread = arc_double.clone();
45 let handle = thread::spawn(move || for_thread.apply(100));
46 println!(
47 "In main thread: arc_double.apply(50) = {}",
48 arc_double.apply(50)
49 );
50 println!("In child thread: result = {}", handle.join().unwrap());
51 println!();
52
53 // ====================================================================
54 // Part 3: RcTransformer - Single-threaded, cloneable
55 // ====================================================================
56 println!("--- RcTransformer ---");
57 let rc_double = RcTransformer::new(|x: i32| x * 2);
58 let rc_cloned = rc_double.clone();
59
60 println!("rc_double.apply(21) = {}", rc_double.apply(21));
61 println!("rc_cloned.apply(42) = {}", rc_cloned.apply(42));
62 println!();
63
64 // ====================================================================
65 // Part 4: Practical Examples
66 // ====================================================================
67 println!("=== Practical Examples ===\n");
68
69 // Example 1: String transformation
70 println!("--- String Transformation ---");
71 let to_upper = BoxTransformer::new(|s: String| s.to_uppercase());
72 println!(
73 "to_upper.apply('hello') = {}",
74 to_upper.apply("hello".to_string())
75 );
76 println!(
77 "to_upper.apply('world') = {}",
78 to_upper.apply("world".to_string())
79 );
80 println!();
81
82 // Example 2: Type conversion pipeline
83 println!("--- Type Conversion Pipeline ---");
84 let parse_int = BoxTransformer::new(|s: String| s.parse::<i32>().unwrap_or(0));
85 let double_int = BoxTransformer::new(|x: i32| x * 2);
86 let to_string = BoxTransformer::new(|x: i32| x.to_string());
87
88 let pipeline = parse_int.and_then(double_int).and_then(to_string);
89 println!(
90 "pipeline.apply('21') = {}",
91 pipeline.apply("21".to_string())
92 );
93 println!();
94
95 // Example 3: Shared transformation logic
96 println!("--- Shared Transformation Logic ---");
97 let square = ArcTransformer::new(|x: i32| x * x);
98
99 // Can be shared across different parts of the program
100 let transformer1 = square.clone();
101 let transformer2 = square.clone();
102
103 println!("transformer1.apply(5) = {}", transformer1.apply(5));
104 println!("transformer2.apply(7) = {}", transformer2.apply(7));
105 println!("square.apply(3) = {}", square.apply(3));
106 println!();
107
108 // Example 4: Transformer registry
109 println!("--- Transformer Registry ---");
110 let mut transformers: HashMap<String, RcTransformer<i32, String>> = HashMap::new();
111
112 transformers.insert(
113 "double".to_string(),
114 RcTransformer::new(|x: i32| format!("Doubled: {}", x * 2)),
115 );
116 transformers.insert(
117 "square".to_string(),
118 RcTransformer::new(|x: i32| format!("Squared: {}", x * x)),
119 );
120
121 if let Some(transformer) = transformers.get("double") {
122 println!("Transformer 'double': {}", transformer.apply(7));
123 }
124 if let Some(transformer) = transformers.get("square") {
125 println!("Transformer 'square': {}", transformer.apply(7));
126 }
127 println!();
128
129 // ====================================================================
130 // Part 5: Trait Usage
131 // ====================================================================
132 println!("=== Trait Usage ===\n");
133
134 fn apply_transformer<F: Transformer<i32, String>>(f: &F, x: i32) -> String {
135 f.apply(x)
136 }
137
138 let to_string = BoxTransformer::new(|x: i32| format!("Value: {}", x));
139 println!("Via trait: {}", apply_transformer(&to_string, 42));
140
141 println!("\n=== Demo Complete ===");
142}20fn main() {
21 println!("=== TransformerOnce Specialized Methods Demo ===\n");
22
23 // ============================================================================
24 // ArcTransformer TransformerOnce specialized methods
25 // ============================================================================
26
27 println!("1. ArcTransformer TransformerOnce specialized methods:");
28
29 let arc_double = ArcTransformer::new(|x: i32| x * 2);
30
31 // Test into_box_once - consumes self
32 let boxed_once = arc_double.clone().into_box_once();
33 println!(
34 " ArcTransformer::into_box_once(): {}",
35 boxed_once.apply_once(21)
36 );
37
38 // Test into_fn_once - consumes self
39 let fn_once = arc_double.clone().into_fn_once();
40 println!(" ArcTransformer::into_fn_once(): {}", fn_once(21));
41
42 // Test to_box_once - borrows self
43 let boxed_once_borrowed = arc_double.to_box_once();
44 println!(
45 " ArcTransformer::to_box_once(): {}",
46 boxed_once_borrowed.apply_once(21)
47 );
48
49 // Test to_fn_once - borrows self
50 let fn_once_borrowed = arc_double.to_fn_once();
51 println!(" ArcTransformer::to_fn_once(): {}", fn_once_borrowed(21));
52
53 // Original transformer still usable after to_xxx methods
54 println!(
55 " Original ArcTransformer still works: {}",
56 arc_double.apply(21)
57 );
58
59 println!();
60
61 // ============================================================================
62 // RcTransformer TransformerOnce specialized methods
63 // ============================================================================
64
65 println!("2. RcTransformer TransformerOnce specialized methods:");
66
67 let rc_triple = RcTransformer::new(|x: i32| x * 3);
68
69 // Test into_box_once - consumes self
70 let boxed_once = rc_triple.clone().into_box_once();
71 println!(
72 " RcTransformer::into_box_once(): {}",
73 boxed_once.apply_once(14)
74 );
75
76 // Test into_fn_once - consumes self
77 let fn_once = rc_triple.clone().into_fn_once();
78 println!(" RcTransformer::into_fn_once(): {}", fn_once(14));
79
80 // Test to_box_once - borrows self
81 let boxed_once_borrowed = rc_triple.to_box_once();
82 println!(
83 " RcTransformer::to_box_once(): {}",
84 boxed_once_borrowed.apply_once(14)
85 );
86
87 // Test to_fn_once - borrows self
88 let fn_once_borrowed = rc_triple.to_fn_once();
89 println!(" RcTransformer::to_fn_once(): {}", fn_once_borrowed(14));
90
91 // Original transformer still usable after to_xxx methods
92 println!(
93 " Original RcTransformer still works: {}",
94 rc_triple.apply(14)
95 );
96
97 println!();
98
99 // ============================================================================
100 // Comparison with default implementations
101 // ============================================================================
102
103 println!("3. Performance comparison (specialized vs default):");
104
105 let arc_square = ArcTransformer::new(|x: i32| x * x);
106
107 // Using specialized method (more efficient)
108 let specialized_box = arc_square.clone().into_box_once();
109 println!(
110 " Specialized into_box_once: {}",
111 specialized_box.apply_once(5)
112 );
113
114 // Using default implementation (less efficient)
115 let default_box = arc_square.clone().into_box_once();
116 println!(" Default into_box_once: {}", default_box.apply_once(5));
117
118 println!();
119
120 // ============================================================================
121 // Thread safety demonstration for ArcTransformer
122 // ============================================================================
123
124 println!("4. Thread safety with ArcTransformer:");
125
126 let arc_shared = ArcTransformer::new(|x: i32| x + 100);
127
128 // Clone for thread safety
129 let arc_clone = arc_shared.clone();
130
131 // Use in different thread context (simulated)
132 let handle = std::thread::spawn(move || {
133 let boxed = arc_clone.into_box_once();
134 boxed.apply_once(50)
135 });
136
137 let result = handle.join().unwrap();
138 println!(" Thread-safe ArcTransformer result: {}", result);
139
140 // Original still usable
141 println!(
142 " Original ArcTransformer still works: {}",
143 arc_shared.apply(50)
144 );
145
146 println!();
147
148 // ============================================================================
149 // String transformation example
150 // ============================================================================
151
152 println!("5. String transformation with specialized methods:");
153
154 let arc_uppercase = ArcTransformer::new(|s: String| s.to_uppercase());
155
156 // Test with string input
157 let test_string = "hello world".to_string();
158
159 // Using specialized methods
160 let boxed_upper = arc_uppercase.clone().into_box_once();
161 let result = boxed_upper.apply_once(test_string.clone());
162 println!(
163 " String transformation: '{}' -> '{}'",
164 test_string, result
165 );
166
167 // Using to_xxx methods (borrowing)
168 let fn_upper = arc_uppercase.to_fn_once();
169 let result2 = fn_upper(test_string.clone());
170 println!(
171 " String transformation (borrowed): '{}' -> '{}'",
172 test_string, result2
173 );
174
175 // Original still usable
176 println!(
177 " Original ArcTransformer still works: '{}'",
178 arc_uppercase.apply(test_string)
179 );
180
181 println!("\n=== Demo completed successfully! ===");
182}Sourcepub fn identity() -> RcTransformer<T, T>
pub fn identity() -> RcTransformer<T, T>
Creates an identity transformer
§Examples
use prism3_function::{RcTransformer, Transformer};
let identity = RcTransformer::<i32, i32>::identity();
assert_eq!(identity.apply(42), 42);Sourcepub fn and_then<S, F>(&self, after: F) -> RcTransformer<T, S>where
S: 'static,
F: Transformer<R, S> + 'static,
pub fn and_then<S, F>(&self, after: F) -> RcTransformer<T, S>where
S: 'static,
F: Transformer<R, S> + 'static,
Chain composition - applies self first, then after
Creates a new transformer that applies this transformer first, then applies the after transformer to the result. Uses &self, so original transformer remains usable.
§Type Parameters
S- The output type of the after transformerF- The type of the after transformer (must implement Transformer<R, S>)
§Parameters
after- The transformer to apply after self. Note: This parameter is passed by value and will transfer ownership. If you need to preserve the original transformer, clone it first (if it implementsClone). Can be:- A closure:
|x: R| -> S - A function pointer:
fn(R) -> S - A
BoxTransformer<R, S> - An
RcTransformer<R, S>(will be moved) - An
ArcTransformer<R, S> - Any type implementing
Transformer<R, S>
- A closure:
§Returns
A new RcTransformer representing the composition
§Examples
§Direct value passing (ownership transfer)
use prism3_function::{RcTransformer, Transformer};
let double = RcTransformer::new(|x: i32| x * 2);
let to_string = RcTransformer::new(|x: i32| x.to_string());
// to_string is moved here
let composed = double.and_then(to_string);
// Original double transformer still usable (uses &self)
assert_eq!(double.apply(21), 42);
assert_eq!(composed.apply(21), "42");
// to_string.apply(5); // Would not compile - moved§Preserving original with clone
use prism3_function::{RcTransformer, Transformer};
let double = RcTransformer::new(|x: i32| x * 2);
let to_string = RcTransformer::new(|x: i32| x.to_string());
// Clone to preserve original
let composed = double.and_then(to_string.clone());
assert_eq!(composed.apply(21), "42");
// Both originals still usable
assert_eq!(double.apply(21), 42);
assert_eq!(to_string.apply(5), "5");Sourcepub fn compose<S, F>(&self, before: F) -> RcTransformer<S, R>where
S: 'static,
F: Transformer<S, T> + 'static,
pub fn compose<S, F>(&self, before: F) -> RcTransformer<S, R>where
S: 'static,
F: Transformer<S, T> + 'static,
Reverse composition - applies before first, then self
Creates a new transformer that applies the before transformer first, then applies this transformer to the result. Uses &self, so original transformer remains usable.
§Type Parameters
S- The input type of the before transformerF- The type of the before transformer (must implement Transformer<S, T>)
§Parameters
before- The transformer to apply before self. Note: This parameter is passed by value and will transfer ownership. If you need to preserve the original transformer, clone it first (if it implementsClone). Can be:- A closure:
|x: S| -> T - A function pointer:
fn(S) -> T - A
BoxTransformer<S, T> - An
RcTransformer<S, T>(will be moved) - An
ArcTransformer<S, T> - Any type implementing
Transformer<S, T>
- A closure:
§Returns
A new RcTransformer representing the composition
§Examples
§Direct value passing (ownership transfer)
use prism3_function::{RcTransformer, Transformer};
let double = RcTransformer::new(|x: i32| x * 2);
let add_one = RcTransformer::new(|x: i32| x + 1);
// add_one is moved here
let composed = double.compose(add_one);
assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
// add_one.apply(3); // Would not compile - moved§Preserving original with clone
use prism3_function::{RcTransformer, Transformer};
let double = RcTransformer::new(|x: i32| x * 2);
let add_one = RcTransformer::new(|x: i32| x + 1);
// Clone to preserve original
let composed = double.compose(add_one.clone());
assert_eq!(composed.apply(5), 12); // (5 + 1) * 2
// Both originals still usable
assert_eq!(double.apply(10), 20);
assert_eq!(add_one.apply(3), 4);Sourcepub fn when<P>(&self, predicate: P) -> RcConditionalTransformer<T, R>where
P: Predicate<T> + 'static,
pub fn when<P>(&self, predicate: P) -> RcConditionalTransformer<T, R>where
P: Predicate<T> + 'static,
Creates a conditional transformer (single-threaded shared version)
Returns a transformer that only executes when a predicate is satisfied.
You must call or_else() to provide an alternative transformer.
§Parameters
predicate- The condition to check. Note: This parameter is passed by value and will transfer ownership. If you need to preserve the original predicate, clone it first (if it implementsClone). Can be:- A closure:
|x: &T| -> bool - A function pointer:
fn(&T) -> bool - A
BoxPredicate<T> - An
RcPredicate<T> - An
ArcPredicate<T> - Any type implementing
Predicate<T>
- A closure:
§Returns
Returns RcConditionalTransformer<T, R>
§Examples
§Basic usage with or_else
use prism3_function::{Transformer, RcTransformer};
let double = RcTransformer::new(|x: i32| x * 2);
let identity = RcTransformer::<i32, i32>::identity();
let conditional = double.when(|x: &i32| *x > 0).or_else(identity);
let conditional_clone = conditional.clone();
assert_eq!(conditional.apply(5), 10);
assert_eq!(conditional_clone.apply(-5), -5);§Preserving predicate with clone
use prism3_function::{Transformer, RcTransformer, RcPredicate};
let double = RcTransformer::new(|x: i32| x * 2);
let is_positive = RcPredicate::new(|x: &i32| *x > 0);
// Clone to preserve original predicate
let conditional = double.when(is_positive.clone())
.or_else(RcTransformer::identity());
assert_eq!(conditional.apply(5), 10);
// Original predicate still usable
assert!(is_positive.test(&3));Source§impl<T, R> RcTransformer<T, R>where
T: 'static,
R: Clone + 'static,
impl<T, R> RcTransformer<T, R>where
T: 'static,
R: Clone + 'static,
Sourcepub fn constant(value: R) -> RcTransformer<T, R>
pub fn constant(value: R) -> RcTransformer<T, R>
Creates a constant transformer
§Examples
use prism3_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> 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
T: 'static,
R: 'static,
fn into_box(self) -> BoxTransformer<T, R>where
T: 'static,
R: 'static,
Source§fn into_rc(self) -> RcTransformer<T, R>where
T: 'static,
R: 'static,
fn into_rc(self) -> RcTransformer<T, R>where
T: 'static,
R: 'static,
Source§fn into_fn(self) -> impl Fn(T) -> Rwhere
T: 'static,
R: 'static,
fn into_fn(self) -> impl Fn(T) -> Rwhere
T: 'static,
R: 'static,
Source§fn to_box(&self) -> BoxTransformer<T, R>where
T: 'static,
R: 'static,
fn to_box(&self) -> BoxTransformer<T, R>where
T: 'static,
R: 'static,
Source§fn to_rc(&self) -> RcTransformer<T, R>where
T: 'static,
R: 'static,
fn to_rc(&self) -> RcTransformer<T, R>where
T: 'static,
R: 'static,
Source§fn to_fn(&self) -> impl Fn(T) -> Rwhere
T: 'static,
R: 'static,
fn to_fn(&self) -> impl Fn(T) -> Rwhere
T: 'static,
R: 'static,
Source§fn into_arc(self) -> ArcTransformer<T, R>
fn into_arc(self) -> ArcTransformer<T, R>
Source§impl<T, R> TransformerOnce<T, R> for RcTransformer<T, R>where
T: 'static,
R: 'static,
impl<T, R> TransformerOnce<T, R> for RcTransformer<T, R>where
T: 'static,
R: 'static,
Source§fn apply_once(self, input: T) -> R
fn apply_once(self, input: T) -> R
Transforms the input value, consuming both self and input
§Parameters
input- The input value (consumed)
§Returns
The transformed output value
§Examples
use prism3_function::{RcTransformer, TransformerOnce};
let double = RcTransformer::new(|x: i32| x * 2);
let result = double.apply_once(21);
assert_eq!(result, 42);§Author
Hu Haixing
Source§fn into_box_once(self) -> BoxTransformerOnce<T, R>where
T: 'static,
R: 'static,
fn into_box_once(self) -> BoxTransformerOnce<T, R>where
T: 'static,
R: 'static,
Converts to BoxTransformerOnce
⚠️ Consumes self: The original transformer becomes unavailable
after calling this method.
§Returns
Returns BoxTransformerOnce<T, R>
§Examples
use prism3_function::{RcTransformer, TransformerOnce};
let double = RcTransformer::new(|x: i32| x * 2);
let boxed = double.into_box_once();
assert_eq!(boxed.apply_once(21), 42);Source§fn into_fn_once(self) -> impl FnOnce(T) -> Rwhere
T: 'static,
R: 'static,
fn into_fn_once(self) -> impl FnOnce(T) -> Rwhere
T: 'static,
R: 'static,
Converts transformer to a closure
⚠️ Consumes self: The original transformer becomes unavailable
after calling this method.
§Returns
Returns a closure that implements FnOnce(T) -> R
§Examples
use prism3_function::{RcTransformer, TransformerOnce};
let double = RcTransformer::new(|x: i32| x * 2);
let func = double.into_fn_once();
assert_eq!(func(21), 42);Source§fn to_box_once(&self) -> BoxTransformerOnce<T, R>where
T: 'static,
R: 'static,
fn to_box_once(&self) -> BoxTransformerOnce<T, R>where
T: 'static,
R: 'static,
Converts to BoxTransformerOnce without consuming self
📌 Borrows &self: The original transformer remains usable
after calling this method.
§Returns
Returns BoxTransformerOnce<T, R>
§Examples
use prism3_function::{RcTransformer, TransformerOnce};
let double = RcTransformer::new(|x: i32| x * 2);
let boxed = double.to_box_once();
assert_eq!(boxed.apply_once(21), 42);
// Original transformer still usable
assert_eq!(double.apply(21), 42);Source§fn to_fn_once(&self) -> impl FnOnce(T) -> Rwhere
T: 'static,
R: 'static,
fn to_fn_once(&self) -> impl FnOnce(T) -> Rwhere
T: 'static,
R: 'static,
Converts transformer to a closure without consuming self
📌 Borrows &self: The original transformer remains usable
after calling this method.
§Returns
Returns a closure that implements FnOnce(T) -> R
§Examples
use prism3_function::{RcTransformer, TransformerOnce};
let double = RcTransformer::new(|x: i32| x * 2);
let func = double.to_fn_once();
assert_eq!(func(21), 42);
// Original transformer still usable
assert_eq!(double.apply(21), 42);