Skip to main content

BoxTransformer

Struct BoxTransformer 

Source
pub struct BoxTransformer<T, R> { /* private fields */ }
Expand description

BoxTransformer - transformer wrapper based on Box<dyn Fn>

A transformer wrapper that provides single ownership with reusable transformation. The transformer consumes the input and can be called multiple times.

§Features

  • Based on: Box<dyn Fn(T) -> R>
  • Ownership: Single ownership, cannot be cloned
  • Reusability: Can be called multiple times (each call consumes its input)
  • Thread Safety: Not thread-safe (no Send + Sync requirement)

§Author

Haixing Hu

Implementations§

Source§

impl<T, R> BoxTransformer<T, R>

Source

pub fn new<F>(f: F) -> Self
where 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?
examples/transformers/transformer_once_demo.rs (line 32)
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
Hide additional examples
examples/transformers/transformer_demo.rs (line 26)
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}
Source

pub fn new_with_name<F>(name: &str, f: F) -> Self
where 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.

Source

pub fn new_with_optional_name<F>(f: F, name: Option<String>) -> Self
where F: Fn(T) -> R + 'static,

Creates a new named transformer with an optional name.

Wraps the provided closure and assigns it an optional name.

Source

pub fn name(&self) -> Option<&str>

Gets the name of this transformer.

§Returns

Returns Some(&str) if a name was set, None otherwise.

Source

pub fn set_name(&mut self, name: &str)

Sets the name of this transformer.

§Parameters
  • name - The name to set for this transformer
Source

pub fn clear_name(&mut self)

Clears the name of this transformer.

Source

pub fn identity() -> BoxTransformer<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.

Examples found in repository?
examples/transformers/transformer_demo.rs (line 31)
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}
Source

pub fn when<P>(self, predicate: P) -> BoxConditionalTransformer<T, R>
where T: 'static, R: 'static, P: Predicate<T> + 'static,

Creates a conditional transformer that executes based on predicate result.

§Parameters
  • predicate - The predicate to determine whether to execute the transformation operation
§Returns

Returns a conditional transformer that only executes when the predicate returns true.

§Examples
use std::sync::Arc;
use std::sync::atomic::{AtomicI32, Ordering};
use qubit_function::transformers::*;

let transformer = BoxTransformer::new({
    |value: i32| value * 2
});

let conditional = transformer.when(|value: &i32| *value > 0).or_else(|value: i32| value);
assert_eq!(conditional.apply(5), 10);  // transformed
assert_eq!(conditional.apply(-1), -1); // identity (unchanged)
Source

pub fn and_then<S, F>(self, after: F) -> BoxTransformer<T, S>
where T: 'static, R: 'static, S: 'static, F: Transformer<R, S> + 'static,

Chains execution with another transformer, executing the current transformer first, then the subsequent transformer.

§Parameters
  • after - The subsequent transformer to execute after the current transformer completes
§Returns

Returns a new transformer that executes the current transformer and the subsequent transformer in sequence.

§Examples
use qubit_function::transformers::*;

let transformer1 = BoxTransformer::new({
    |value: i32| value + 1
});

let transformer2 = BoxTransformer::new({
    |value: i32| value * 2
});

let chained = transformer1.and_then(transformer2);
assert_eq!(chained.apply(5), 12); // (5 + 1) * 2 = 12
Examples found in repository?
examples/transformers/fn_transformer_ops_demo.rs (line 38)
19fn main() {
20    println!("=== FnTransformerOps Example ===\n");
21
22    // 1. Basic and_then composition
23    println!("1. Basic and_then composition:");
24    let double = |x: i32| x * 2;
25    let to_string = |x: i32| x.to_string();
26    let composed = double.and_then(to_string);
27    println!(
28        "   double.and_then(to_string).apply(21) = {}",
29        composed.apply(21)
30    );
31    println!();
32
33    // 2. Chained and_then composition
34    println!("2. Chained and_then composition:");
35    let add_one = |x: i32| x + 1;
36    let double = |x: i32| x * 2;
37    let to_string = |x: i32| x.to_string();
38    let chained = add_one.and_then(double).and_then(to_string);
39    println!(
40        "   add_one.and_then(double).and_then(to_string).apply(5) = {}",
41        chained.apply(5)
42    ); // (5 + 1) * 2 = 12
43    println!();
44
45    // 3. compose reverse composition
46    println!("3. compose reverse composition:");
47    let double = |x: i32| x * 2;
48    let add_one = |x: i32| x + 1;
49    let composed = double.compose(add_one);
50    println!(
51        "   double.compose(add_one).apply(5) = {}",
52        composed.apply(5)
53    ); // (5 + 1) * 2 = 12
54    println!();
55
56    // 4. Conditional transformation when
57    println!("4. Conditional transformation when:");
58    let double = |x: i32| x * 2;
59    let conditional = double.when(|x: &i32| *x > 0).or_else(|x: i32| -x);
60    println!("   double.when(x > 0).or_else(negate):");
61    println!("     transform(5) = {}", conditional.apply(5)); // 10
62    println!("     transform(-5) = {}", conditional.apply(-5)); // 5
63    println!();
64
65    // 5. Complex composition
66    println!("5. Complex composition:");
67    let add_one = |x: i32| x + 1;
68    let double = |x: i32| x * 2;
69    let triple = |x: i32| x * 3;
70    let to_string = |x: i32| x.to_string();
71
72    let complex = add_one
73        .and_then(double.when(|x: &i32| *x > 5).or_else(triple))
74        .and_then(to_string);
75
76    println!("   add_one.and_then(double.when(x > 5).or_else(triple)).and_then(to_string):");
77    println!("     transform(1) = {}", complex.apply(1)); // (1 + 1) = 2 <= 5, so 2 * 3 = 6
78    println!("     transform(5) = {}", complex.apply(5)); // (5 + 1) = 6 > 5, so 6 * 2 = 12
79    println!("     transform(10) = {}", complex.apply(10)); // (10 + 1) = 11 > 5, so 11 * 2 = 22
80    println!();
81
82    // 6. Type conversion
83    println!("6. Type conversion:");
84    let to_string = |x: i32| x.to_string();
85    let get_length = |s: String| s.len();
86    let length_transformer = to_string.and_then(get_length);
87    println!(
88        "   to_string.and_then(get_length).apply(12345) = {}",
89        length_transformer.apply(12345)
90    ); // 5
91    println!();
92
93    // 7. Closures that capture environment
94    println!("7. Closures that capture environment:");
95    let multiplier = 3;
96    let multiply = move |x: i32| x * multiplier;
97    let add_ten = |x: i32| x + 10;
98    let with_capture = multiply.and_then(add_ten);
99    println!(
100        "   multiply(3).and_then(add_ten).apply(5) = {}",
101        with_capture.apply(5)
102    ); // 5 * 3 + 10 = 25
103    println!();
104
105    // 8. Function pointers
106    println!("8. Function pointers:");
107    fn double_fn(x: i32) -> i32 {
108        x * 2
109    }
110    fn add_one_fn(x: i32) -> i32 {
111        x + 1
112    }
113    let fn_composed = double_fn.and_then(add_one_fn);
114    println!(
115        "   double_fn.and_then(add_one_fn).apply(5) = {}",
116        fn_composed.apply(5)
117    ); // 5 * 2 + 1 = 11
118    println!();
119
120    // 9. Multi-conditional transformation
121    println!("9. Multi-conditional transformation:");
122    let abs = |x: i32| x.abs();
123    let double = |x: i32| x * 2;
124    let transformer = abs.when(|x: &i32| *x < 0).or_else(double);
125    println!("   abs.when(x < 0).or_else(double):");
126    println!("     transform(-5) = {}", transformer.apply(-5)); // abs(-5) = 5
127    println!("     transform(5) = {}", transformer.apply(5)); // 5 * 2 = 10
128    println!("     transform(0) = {}", transformer.apply(0)); // 0 * 2 = 0
129    println!();
130
131    println!("=== Example completed ===");
132}
More examples
Hide additional examples
examples/transformers/transformer_demo.rs (line 93)
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}
Source§

impl<T, R> BoxTransformer<T, R>

Source

pub fn constant(value: R) -> BoxTransformer<T, R>
where R: Clone + 'static,

Creates a constant transformer

§Examples

/// rust /// use qubit_function::{BoxTransformer, Transformer}; /// /// let constant = BoxTransformer::constant("hello"); /// assert_eq!(constant.apply(123), "hello"); ///

Examples found in repository?
examples/transformers/transformer_demo.rs (line 34)
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}

Trait Implementations§

Source§

impl<T, R> Debug for BoxTransformer<T, R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T, R> Display for BoxTransformer<T, R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T, R> Transformer<T, R> for BoxTransformer<T, R>

Source§

fn apply(&self, input: T) -> R

Applies the transformation to the input value to produce an output value Read more
Source§

fn into_box(self) -> BoxTransformer<T, R>

Converts to BoxTransformer Read more
Source§

fn into_rc(self) -> RcTransformer<T, R>
where Self: 'static,

Converts to RcTransformer Read more
Source§

fn into_fn(self) -> impl Fn(T) -> R

Converts transformer to a closure Read more
Source§

fn into_once(self) -> BoxTransformerOnce<T, R>
where Self: 'static,

Converts to BoxTransformerOnce. Read more
Source§

fn into_arc(self) -> ArcTransformer<T, R>
where Self: Sized + Send + Sync + 'static,

Converts to ArcTransformer Read more

Auto Trait Implementations§

§

impl<T, R> Freeze for BoxTransformer<T, R>

§

impl<T, R> !RefUnwindSafe for BoxTransformer<T, R>

§

impl<T, R> !Send for BoxTransformer<T, R>

§

impl<T, R> !Sync for BoxTransformer<T, R>

§

impl<T, R> Unpin for BoxTransformer<T, R>

§

impl<T, R> UnsafeUnpin for BoxTransformer<T, R>

§

impl<T, R> !UnwindSafe for BoxTransformer<T, R>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<F, T> UnaryOperator<T> for F
where F: Transformer<T, T>,