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

Hu Haixing

Implementations§

Source§

impl<T, R> BoxTransformer<T, R>
where T: 'static, R: 'static,

Source

pub fn new<F>(f: F) -> Self
where F: Fn(T) -> R + 'static,

Creates a new BoxTransformer

§Parameters
  • f - The closure or function to wrap
§Examples
use prism3_function::{BoxTransformer, Transformer};

let double = BoxTransformer::new(|x: i32| x * 2);
assert_eq!(double.apply(21), 42);
Examples found in repository?
examples/transformer_once_demo.rs (line 27)
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
Hide additional examples
examples/transformer_demo.rs (line 21)
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}
Source

pub fn identity() -> BoxTransformer<T, T>

Creates an identity transformer

§Examples
use prism3_function::{BoxTransformer, Transformer};

let identity = BoxTransformer::<i32, i32>::identity();
assert_eq!(identity.apply(42), 42);
Examples found in repository?
examples/transformer_demo.rs (line 26)
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}
Source

pub fn and_then<S, F>(self, after: F) -> BoxTransformer<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. Consumes self.

§Type Parameters
  • S - The output type of the after transformer
  • F - 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 implements Clone). Can be:
    • A closure: |x: R| -> S
    • A function pointer: fn(R) -> S
    • A BoxTransformer<R, S>
    • An RcTransformer<R, S>
    • An ArcTransformer<R, S>
    • Any type implementing Transformer<R, S>
§Returns

A new BoxTransformer representing the composition

§Examples
§Direct value passing (ownership transfer)
use prism3_function::{BoxTransformer, Transformer};

let double = BoxTransformer::new(|x: i32| x * 2);
let to_string = BoxTransformer::new(|x: i32| x.to_string());

// to_string is moved here
let composed = double.and_then(to_string);
assert_eq!(composed.apply(21), "42");
// to_string.apply(5); // Would not compile - moved
§Preserving original with clone
use prism3_function::{BoxTransformer, Transformer};

let double = BoxTransformer::new(|x: i32| x * 2);
let to_string = BoxTransformer::new(|x: i32| x.to_string());

// Clone to preserve original
let composed = double.and_then(to_string.clone());
assert_eq!(composed.apply(21), "42");

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

pub fn compose<S, F>(self, before: F) -> BoxTransformer<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. Consumes self.

§Type Parameters
  • S - The input type of the before transformer
  • F - 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 implements Clone). Can be:
    • A closure: |x: S| -> T
    • A function pointer: fn(S) -> T
    • A BoxTransformer<S, T>
    • An RcTransformer<S, T>
    • An ArcTransformer<S, T>
    • Any type implementing Transformer<S, T>
§Returns

A new BoxTransformer representing the composition

§Examples
§Direct value passing (ownership transfer)
use prism3_function::{BoxTransformer, Transformer};

let double = BoxTransformer::new(|x: i32| x * 2);
let add_one = BoxTransformer::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::{BoxTransformer, Transformer};

let double = BoxTransformer::new(|x: i32| x * 2);
let add_one = BoxTransformer::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

// Original still usable
assert_eq!(add_one.apply(3), 4);
Source

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

Creates a conditional transformer

Returns a transformer that only executes when a predicate is satisfied. You must call or_else() to provide an alternative transformer for when the condition is not satisfied.

§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 implements Clone). 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>
§Returns

Returns BoxConditionalTransformer<T, R>

§Examples
§Basic usage with or_else
use prism3_function::{Transformer, BoxTransformer};

let double = BoxTransformer::new(|x: i32| x * 2);
let identity = BoxTransformer::<i32, i32>::identity();
let conditional = double.when(|x: &i32| *x > 0).or_else(identity);

assert_eq!(conditional.apply(5), 10);
assert_eq!(conditional.apply(-5), -5); // identity
§Preserving predicate with clone
use prism3_function::{Transformer, BoxTransformer, BoxPredicate};

let double = BoxTransformer::new(|x: i32| x * 2);
let is_positive = BoxPredicate::new(|x: &i32| *x > 0);

// Clone to preserve original predicate
let conditional = double.when(is_positive.clone())
    .or_else(BoxTransformer::identity());

assert_eq!(conditional.apply(5), 10);

// Original predicate still usable
assert!(is_positive.test(&3));
Source§

impl<T, R> BoxTransformer<T, R>
where T: 'static, R: Clone + 'static,

Source

pub fn constant(value: R) -> BoxTransformer<T, R>

Creates a constant transformer

§Examples
use prism3_function::{BoxTransformer, Transformer};

let constant = BoxTransformer::constant("hello");
assert_eq!(constant.apply(123), "hello");
Examples found in repository?
examples/transformer_demo.rs (line 29)
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}

Trait Implementations§

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>
where T: 'static, R: 'static,

Converts to BoxTransformer Read more
Source§

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

Converts to RcTransformer Read more
Source§

fn into_fn(self) -> impl Fn(T) -> R
where T: 'static, R: 'static,

Converts transformer to a closure Read more
Source§

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

Converts to ArcTransformer Read more
Source§

impl<T, R> TransformerOnce<T, R> for BoxTransformer<T, R>
where T: 'static, R: 'static,

Source§

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::{BoxTransformer, TransformerOnce};

let double = BoxTransformer::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 Self: Sized + 'static, T: 'static, R: 'static,

Converts to BoxTransformerOnce Read more
Source§

fn into_fn_once(self) -> impl FnOnce(T) -> R
where Self: Sized + 'static, T: 'static, R: 'static,

Converts transformer to a closure 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> !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, 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>, T: 'static,

Source§

impl<F, T> UnaryOperatorOnce<T> for F
where F: TransformerOnce<T, T>, T: 'static,