Skip to main content

StatefulTransformer

Trait StatefulTransformer 

Source
pub trait StatefulTransformer<T, R> {
Show 13 methods // Required method fn apply(&mut self, input: T) -> R; // Provided methods fn into_box(self) -> BoxStatefulTransformer<T, R> where Self: Sized + 'static { ... } fn into_rc(self) -> RcStatefulTransformer<T, R> where Self: Sized + 'static { ... } fn into_arc(self) -> ArcStatefulTransformer<T, R> where Self: Sized + Send + 'static { ... } fn into_fn(self) -> impl FnMut(T) -> R where Self: Sized + 'static { ... } fn into_mut_fn(self) -> impl FnMut(T) -> R where Self: Sized + 'static { ... } fn into_once(self) -> BoxTransformerOnce<T, R> where Self: Sized + 'static { ... } fn to_box(&self) -> BoxStatefulTransformer<T, R> where Self: Sized + Clone + 'static { ... } fn to_rc(&self) -> RcStatefulTransformer<T, R> where Self: Sized + Clone + 'static { ... } fn to_arc(&self) -> ArcStatefulTransformer<T, R> where Self: Sized + Clone + Send + 'static { ... } fn to_fn(&self) -> impl FnMut(T) -> R where Self: Sized + Clone + 'static { ... } fn to_mut_fn(&self) -> impl FnMut(T) -> R where Self: Sized + Clone + 'static { ... } fn to_once(&self) -> BoxTransformerOnce<T, R> where Self: Sized + Clone + 'static { ... }
}
Expand description

StatefulTransformer trait - transforms values from type T to type R with state

Defines the behavior of a stateful transformation: converting a value of type T to a value of type R by consuming the input while allowing modification of internal state. This is analogous to FnMut(T) -> R in Rust’s standard library.

§Type Parameters

  • T - The type of the input value (consumed)
  • R - The type of the output value

§Author

Haixing Hu

Required Methods§

Source

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

Applies the transformation to the input value to produce an output value

§Parameters
  • input - The input value to transform (consumed)
§Returns

The transformed output value

Provided Methods§

Source

fn into_box(self) -> BoxStatefulTransformer<T, R>
where Self: Sized + 'static,

Converts to BoxStatefulTransformer

⚠️ Consumes self: The original transformer becomes unavailable after calling this method.

§Returns

Returns BoxStatefulTransformer<T, R>

§Default Implementation

The default implementation wraps self in a BoxStatefulTransformer by creating a new closure that calls self.apply(). This is a lightweight adapter, but it is not strictly zero-cost.

§Examples
use qubit_function::{StatefulTransformer, BoxStatefulTransformer};

struct CustomTransformer {
    multiplier: i32,
}

impl StatefulTransformer<i32, i32> for CustomTransformer {
    fn apply(&mut self, input: i32) -> i32 {
        self.multiplier += 1;
        input * self.multiplier
    }
}

let transformer = CustomTransformer { multiplier: 0 };
let mut boxed = transformer.into_box();
assert_eq!(boxed.apply(10), 10);  // 10 * 1
assert_eq!(boxed.apply(10), 20);  // 10 * 2
Examples found in repository?
examples/transformers/stateful_transformer_demo.rs (line 194)
23fn main() {
24    println!("=== StatefulTransformer Demo ===\n");
25
26    // 1. Basic BoxStatefulTransformer with state
27    println!("1. BoxStatefulTransformer with stateful counter:");
28    let mut counter = 0;
29    let mut mapper = BoxStatefulTransformer::new(move |x: i32| {
30        counter += 1;
31        format!("Item #{}: {}", counter, x)
32    });
33
34    println!("  {}", mapper.apply(100)); // Item #1: 100
35    println!("  {}", mapper.apply(200)); // Item #2: 200
36    println!("  {}", mapper.apply(300)); // Item #3: 300
37
38    // 2. Composing mappers with and_then
39    println!("\n2. Composing mappers with and_then:");
40    let mut counter1 = 0;
41    let mapper1 = BoxStatefulTransformer::new(move |x: i32| {
42        counter1 += 1;
43        x + counter1
44    });
45
46    let mut counter2 = 0;
47    let mapper2 = BoxStatefulTransformer::new(move |x: i32| {
48        counter2 += 1;
49        x * counter2
50    });
51
52    let mut composed = mapper1.and_then(mapper2);
53    println!("  First call:  {}", composed.apply(10)); // (10 + 1) * 1 = 11
54    println!("  Second call: {}", composed.apply(10)); // (10 + 2) * 2 = 24
55    println!("  Third call:  {}", composed.apply(10)); // (10 + 3) * 3 = 39
56
57    // 3. Conditional mapping with when/or_else
58    println!("\n3. Conditional mapping:");
59    let mut high_count = 0;
60    let mut low_count = 0;
61
62    let mut conditional = BoxStatefulTransformer::new(move |x: i32| {
63        high_count += 1;
64        format!("High[{}]: {} * 2 = {}", high_count, x, x * 2)
65    })
66    .when(|x: &i32| *x >= 10)
67    .or_else(move |x| {
68        low_count += 1;
69        format!("Low[{}]: {} + 1 = {}", low_count, x, x + 1)
70    });
71
72    println!("  {}", conditional.apply(15)); // High[1]: 15 * 2 = 30
73    println!("  {}", conditional.apply(5)); // Low[1]: 5 + 1 = 6
74    println!("  {}", conditional.apply(20)); // High[2]: 20 * 2 = 40
75
76    // 4. RcStatefulTransformer for cloneable mappers
77    println!("\n4. RcStatefulTransformer (cloneable, single-threaded):");
78    let mut counter = 0;
79    let mapper = RcStatefulTransformer::new(move |x: i32| {
80        counter += 1;
81        x + counter
82    });
83
84    let mut mapper1 = mapper.clone();
85    let mut mapper2 = mapper.clone();
86
87    println!("  mapper1: {}", mapper1.apply(10)); // 11
88    println!("  mapper2: {}", mapper2.apply(10)); // 12
89    println!("  mapper1: {}", mapper1.apply(10)); // 13
90
91    // 5. ArcStatefulTransformer for thread-safe mappers
92    println!("\n5. ArcStatefulTransformer (thread-safe):");
93    let mut counter = 0;
94    let mapper = ArcStatefulTransformer::new(move |x: i32| {
95        counter += 1;
96        format!("Result[{}]: {}", counter, x * 2)
97    });
98
99    let mut mapper_clone = mapper.clone();
100    println!("  Original: {}", mapper_clone.apply(5)); // Result[1]: 10
101    println!("  Clone:    {}", mapper_clone.apply(7)); // Result[2]: 14
102
103    // 6. Using FnStatefulTransformerOps extension trait
104    println!("\n6. Using FnStatefulTransformerOps extension trait:");
105    let mut count = 0;
106    let mut mapper = (move |x: i32| {
107        count += 1;
108        x + count
109    })
110    .and_then(|x| x * 2);
111
112    println!("  {}", mapper.apply(10)); // (10 + 1) * 2 = 22
113    println!("  {}", mapper.apply(10)); // (10 + 2) * 2 = 24
114
115    // 7. Building a complex pipeline
116    println!("\n7. Complex processing pipeline:");
117    let mut step1_count = 0;
118    let step1 = BoxStatefulTransformer::new(move |x: i32| {
119        step1_count += 1;
120        format!("Step1[{}]: {}", step1_count, x)
121    });
122
123    let mut step2_count = 0;
124    let step2 = BoxStatefulTransformer::new(move |s: String| {
125        step2_count += 1;
126        format!("{} -> Step2[{}]", s, step2_count)
127    });
128
129    let mut step3_count = 0;
130    let step3 = BoxStatefulTransformer::new(move |s: String| {
131        step3_count += 1;
132        format!("{} -> Step3[{}]", s, step3_count)
133    });
134
135    let mut pipeline = step1.and_then(step2).and_then(step3);
136
137    println!("  {}", pipeline.apply(100));
138    println!("  {}", pipeline.apply(200));
139
140    // 7. TransformerOnce implementation - consuming transformers
141    println!("\n7. TransformerOnce implementation - consuming StatefulTransformers:");
142
143    // BoxStatefulTransformer can be consumed as TransformerOnce
144    let mut counter = 0;
145    let mut box_mapper = BoxStatefulTransformer::new(move |x: i32| {
146        counter += 1;
147        x * counter
148    });
149    println!(
150        "  BoxStatefulTransformer consumed once: {}",
151        box_mapper.apply(10)
152    ); // 10 * 1 = 10
153
154    // RcStatefulTransformer can be consumed as TransformerOnce
155    let mut counter = 0;
156    let mut rc_mapper = RcStatefulTransformer::new(move |x: i32| {
157        counter += 1;
158        x + counter
159    });
160    let rc_clone = rc_mapper.clone(); // Clone before consuming
161    println!(
162        "  RcStatefulTransformer consumed once: {}",
163        rc_mapper.apply(10)
164    ); // 10 + 1 = 11
165    println!("  RcStatefulTransformer clone still works: {}", {
166        let mut rc_clone_for_call = rc_clone.clone();
167        rc_clone_for_call.apply(10)
168    }); // 10 + 2 = 12
169
170    // ArcStatefulTransformer can be consumed as TransformerOnce
171    let mut counter = 0;
172    let mut arc_mapper = ArcStatefulTransformer::new(move |x: i32| {
173        counter += 1;
174        x * counter
175    });
176    let arc_clone = arc_mapper.clone(); // Clone before consuming
177    println!(
178        "  ArcStatefulTransformer consumed once: {}",
179        arc_mapper.apply(10)
180    ); // 10 * 1 = 10
181    println!("  ArcStatefulTransformer clone still works: {}", {
182        let mut arc_clone_for_call = arc_clone.clone();
183        arc_clone_for_call.apply(10)
184    }); // 10 * 2 = 20
185
186    // 8. Converting to BoxTransformerOnce
187    println!("\n8. Converting StatefulTransformers to BoxTransformerOnce:");
188
189    let mut counter = 0;
190    let mapper = BoxStatefulTransformer::new(move |x: i32| {
191        counter += 1;
192        x * counter
193    });
194    let mut once_mapper = mapper.into_box();
195    println!(
196        "  BoxStatefulTransformer->BoxTransformerOnce: {}",
197        once_mapper.apply(5)
198    ); // 5 * 1 = 5
199
200    // RcStatefulTransformer can use to_box() to preserve original
201    let mut counter = 0;
202    let rc_mapper = RcStatefulTransformer::new(move |x: i32| {
203        counter += 1;
204        x * counter
205    });
206    let mut once_mapper = rc_mapper.to_box();
207    println!(
208        "  RcStatefulTransformer->BoxTransformerOnce: {}",
209        once_mapper.apply(5)
210    ); // 5 * 1 = 5
211    println!("  Original RcStatefulTransformer still works: {}", {
212        let mut rc_original_for_call = rc_mapper.clone();
213        rc_original_for_call.apply(5)
214    }); // 5 * 2 = 10
215
216    println!("\n=== Demo Complete ===");
217}
Source

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

Converts to RcStatefulTransformer

⚠️ Consumes self: The original transformer becomes unavailable after calling this method.

§Returns

Returns RcStatefulTransformer<T, R>

§Default Implementation

The default implementation first converts to BoxStatefulTransformer using into_box(), then wraps it in RcStatefulTransformer. Specific implementations may override this for better efficiency.

§Examples
use qubit_function::{StatefulTransformer, RcStatefulTransformer};

struct CustomTransformer {
    multiplier: i32,
}

impl StatefulTransformer<i32, i32> for CustomTransformer {
    fn apply(&mut self, input: i32) -> i32 {
        self.multiplier += 1;
        input * self.multiplier
    }
}

let transformer = CustomTransformer { multiplier: 0 };
let mut rc_transformer = transformer.into_rc();
assert_eq!(rc_transformer.apply(10), 10);  // 10 * 1
assert_eq!(rc_transformer.apply(10), 20);  // 10 * 2
Source

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

Converts to ArcStatefulTransformer

⚠️ Consumes self: The original transformer becomes unavailable after calling this method.

§Returns

Returns ArcStatefulTransformer<T, R>

§Default Implementation

The default implementation wraps self in an ArcStatefulTransformer by creating a new closure that calls self.apply(). Note that this requires self to implement Send due to Arc’s thread-safety requirements.

§Examples
use qubit_function::{StatefulTransformer, ArcStatefulTransformer};

struct CustomTransformer {
    multiplier: i32,
}

impl StatefulTransformer<i32, i32> for CustomTransformer {
    fn apply(&mut self, input: i32) -> i32 {
        self.multiplier += 1;
        input * self.multiplier
    }
}

let transformer = CustomTransformer { multiplier: 0 };
let mut arc_transformer = transformer.into_arc();
assert_eq!(arc_transformer.apply(10), 10);  // 10 * 1
assert_eq!(arc_transformer.apply(10), 20);  // 10 * 2
Source

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

Converts to a closure implementing FnMut(T) -> R

⚠️ Consumes self: The original transformer becomes unavailable after calling this method.

§Returns

Returns an implementation of FnMut(T) -> R

§Default Implementation

The default implementation creates a new closure that calls self.apply(). Specific implementations may override this for better efficiency.

§Examples
use qubit_function::{StatefulTransformer, BoxStatefulTransformer};

let transformer = BoxStatefulTransformer::new(|x: i32| x * 2);
let mut closure = transformer.into_fn();
assert_eq!(closure(10), 20);
assert_eq!(closure(15), 30);
Source

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

Converts transformer to a mutable closure (FnMut) with an explicit method name.

This is a naming alias of StatefulTransformer::into_fn to make the mutability of the returned closure explicit.

Source

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

Converts to BoxTransformerOnce.

This method has a default implementation that wraps the transformer in a BoxTransformerOnce. Custom implementations can override this method for optimization purposes.

§Returns

A new BoxTransformerOnce<T, R> instance

§Examples
use qubit_function::{StatefulTransformer, TransformerOnce};

let closure = |x: i32| x * 2;
let once = closure.into_once();
assert_eq!(once.apply(5), 10);
Source

fn to_box(&self) -> BoxStatefulTransformer<T, R>
where Self: Sized + Clone + 'static,

Non-consuming conversion to BoxStatefulTransformer.

Default implementation requires Self: Clone and wraps a cloned instance in a RefCell so the returned transformer can mutate state across calls.

Examples found in repository?
examples/transformers/stateful_transformer_demo.rs (line 206)
23fn main() {
24    println!("=== StatefulTransformer Demo ===\n");
25
26    // 1. Basic BoxStatefulTransformer with state
27    println!("1. BoxStatefulTransformer with stateful counter:");
28    let mut counter = 0;
29    let mut mapper = BoxStatefulTransformer::new(move |x: i32| {
30        counter += 1;
31        format!("Item #{}: {}", counter, x)
32    });
33
34    println!("  {}", mapper.apply(100)); // Item #1: 100
35    println!("  {}", mapper.apply(200)); // Item #2: 200
36    println!("  {}", mapper.apply(300)); // Item #3: 300
37
38    // 2. Composing mappers with and_then
39    println!("\n2. Composing mappers with and_then:");
40    let mut counter1 = 0;
41    let mapper1 = BoxStatefulTransformer::new(move |x: i32| {
42        counter1 += 1;
43        x + counter1
44    });
45
46    let mut counter2 = 0;
47    let mapper2 = BoxStatefulTransformer::new(move |x: i32| {
48        counter2 += 1;
49        x * counter2
50    });
51
52    let mut composed = mapper1.and_then(mapper2);
53    println!("  First call:  {}", composed.apply(10)); // (10 + 1) * 1 = 11
54    println!("  Second call: {}", composed.apply(10)); // (10 + 2) * 2 = 24
55    println!("  Third call:  {}", composed.apply(10)); // (10 + 3) * 3 = 39
56
57    // 3. Conditional mapping with when/or_else
58    println!("\n3. Conditional mapping:");
59    let mut high_count = 0;
60    let mut low_count = 0;
61
62    let mut conditional = BoxStatefulTransformer::new(move |x: i32| {
63        high_count += 1;
64        format!("High[{}]: {} * 2 = {}", high_count, x, x * 2)
65    })
66    .when(|x: &i32| *x >= 10)
67    .or_else(move |x| {
68        low_count += 1;
69        format!("Low[{}]: {} + 1 = {}", low_count, x, x + 1)
70    });
71
72    println!("  {}", conditional.apply(15)); // High[1]: 15 * 2 = 30
73    println!("  {}", conditional.apply(5)); // Low[1]: 5 + 1 = 6
74    println!("  {}", conditional.apply(20)); // High[2]: 20 * 2 = 40
75
76    // 4. RcStatefulTransformer for cloneable mappers
77    println!("\n4. RcStatefulTransformer (cloneable, single-threaded):");
78    let mut counter = 0;
79    let mapper = RcStatefulTransformer::new(move |x: i32| {
80        counter += 1;
81        x + counter
82    });
83
84    let mut mapper1 = mapper.clone();
85    let mut mapper2 = mapper.clone();
86
87    println!("  mapper1: {}", mapper1.apply(10)); // 11
88    println!("  mapper2: {}", mapper2.apply(10)); // 12
89    println!("  mapper1: {}", mapper1.apply(10)); // 13
90
91    // 5. ArcStatefulTransformer for thread-safe mappers
92    println!("\n5. ArcStatefulTransformer (thread-safe):");
93    let mut counter = 0;
94    let mapper = ArcStatefulTransformer::new(move |x: i32| {
95        counter += 1;
96        format!("Result[{}]: {}", counter, x * 2)
97    });
98
99    let mut mapper_clone = mapper.clone();
100    println!("  Original: {}", mapper_clone.apply(5)); // Result[1]: 10
101    println!("  Clone:    {}", mapper_clone.apply(7)); // Result[2]: 14
102
103    // 6. Using FnStatefulTransformerOps extension trait
104    println!("\n6. Using FnStatefulTransformerOps extension trait:");
105    let mut count = 0;
106    let mut mapper = (move |x: i32| {
107        count += 1;
108        x + count
109    })
110    .and_then(|x| x * 2);
111
112    println!("  {}", mapper.apply(10)); // (10 + 1) * 2 = 22
113    println!("  {}", mapper.apply(10)); // (10 + 2) * 2 = 24
114
115    // 7. Building a complex pipeline
116    println!("\n7. Complex processing pipeline:");
117    let mut step1_count = 0;
118    let step1 = BoxStatefulTransformer::new(move |x: i32| {
119        step1_count += 1;
120        format!("Step1[{}]: {}", step1_count, x)
121    });
122
123    let mut step2_count = 0;
124    let step2 = BoxStatefulTransformer::new(move |s: String| {
125        step2_count += 1;
126        format!("{} -> Step2[{}]", s, step2_count)
127    });
128
129    let mut step3_count = 0;
130    let step3 = BoxStatefulTransformer::new(move |s: String| {
131        step3_count += 1;
132        format!("{} -> Step3[{}]", s, step3_count)
133    });
134
135    let mut pipeline = step1.and_then(step2).and_then(step3);
136
137    println!("  {}", pipeline.apply(100));
138    println!("  {}", pipeline.apply(200));
139
140    // 7. TransformerOnce implementation - consuming transformers
141    println!("\n7. TransformerOnce implementation - consuming StatefulTransformers:");
142
143    // BoxStatefulTransformer can be consumed as TransformerOnce
144    let mut counter = 0;
145    let mut box_mapper = BoxStatefulTransformer::new(move |x: i32| {
146        counter += 1;
147        x * counter
148    });
149    println!(
150        "  BoxStatefulTransformer consumed once: {}",
151        box_mapper.apply(10)
152    ); // 10 * 1 = 10
153
154    // RcStatefulTransformer can be consumed as TransformerOnce
155    let mut counter = 0;
156    let mut rc_mapper = RcStatefulTransformer::new(move |x: i32| {
157        counter += 1;
158        x + counter
159    });
160    let rc_clone = rc_mapper.clone(); // Clone before consuming
161    println!(
162        "  RcStatefulTransformer consumed once: {}",
163        rc_mapper.apply(10)
164    ); // 10 + 1 = 11
165    println!("  RcStatefulTransformer clone still works: {}", {
166        let mut rc_clone_for_call = rc_clone.clone();
167        rc_clone_for_call.apply(10)
168    }); // 10 + 2 = 12
169
170    // ArcStatefulTransformer can be consumed as TransformerOnce
171    let mut counter = 0;
172    let mut arc_mapper = ArcStatefulTransformer::new(move |x: i32| {
173        counter += 1;
174        x * counter
175    });
176    let arc_clone = arc_mapper.clone(); // Clone before consuming
177    println!(
178        "  ArcStatefulTransformer consumed once: {}",
179        arc_mapper.apply(10)
180    ); // 10 * 1 = 10
181    println!("  ArcStatefulTransformer clone still works: {}", {
182        let mut arc_clone_for_call = arc_clone.clone();
183        arc_clone_for_call.apply(10)
184    }); // 10 * 2 = 20
185
186    // 8. Converting to BoxTransformerOnce
187    println!("\n8. Converting StatefulTransformers to BoxTransformerOnce:");
188
189    let mut counter = 0;
190    let mapper = BoxStatefulTransformer::new(move |x: i32| {
191        counter += 1;
192        x * counter
193    });
194    let mut once_mapper = mapper.into_box();
195    println!(
196        "  BoxStatefulTransformer->BoxTransformerOnce: {}",
197        once_mapper.apply(5)
198    ); // 5 * 1 = 5
199
200    // RcStatefulTransformer can use to_box() to preserve original
201    let mut counter = 0;
202    let rc_mapper = RcStatefulTransformer::new(move |x: i32| {
203        counter += 1;
204        x * counter
205    });
206    let mut once_mapper = rc_mapper.to_box();
207    println!(
208        "  RcStatefulTransformer->BoxTransformerOnce: {}",
209        once_mapper.apply(5)
210    ); // 5 * 1 = 5
211    println!("  Original RcStatefulTransformer still works: {}", {
212        let mut rc_original_for_call = rc_mapper.clone();
213        rc_original_for_call.apply(5)
214    }); // 5 * 2 = 10
215
216    println!("\n=== Demo Complete ===");
217}
Source

fn to_rc(&self) -> RcStatefulTransformer<T, R>
where Self: Sized + Clone + 'static,

Non-consuming conversion to RcStatefulTransformer.

Default implementation clones self into an Rc<RefCell<_>> so the resulting transformer can be shared within a single thread.

Source

fn to_arc(&self) -> ArcStatefulTransformer<T, R>
where Self: Sized + Clone + Send + 'static,

Non-consuming conversion to ArcStatefulTransformer (thread-safe).

Default implementation requires Self: Clone + Send + Sync and wraps the cloned instance in Arc<Mutex<_>> so it can be used across threads.

Source

fn to_fn(&self) -> impl FnMut(T) -> R
where Self: Sized + Clone + 'static,

Non-consuming conversion to a closure (FnMut(T) -> R).

Default implementation clones self into a RefCell and returns a closure that calls apply on the interior mutable value.

Source

fn to_mut_fn(&self) -> impl FnMut(T) -> R
where Self: Sized + Clone + 'static,

Non-consuming conversion to a mutable closure (FnMut) with an explicit method name.

This is a naming alias of StatefulTransformer::to_fn and preserves the same clone-based behavior.

Source

fn to_once(&self) -> BoxTransformerOnce<T, R>
where Self: Sized + Clone + 'static,

Creates a BoxTransformerOnce from a cloned transformer

Uses Clone to obtain an owned copy and converts it into a BoxTransformerOnce. Requires Self: Clone. Custom implementations can override this for better performance.

Implementors§

Source§

impl<T, R> StatefulTransformer<T, R> for ArcStatefulTransformer<T, R>

Source§

impl<T, R> StatefulTransformer<T, R> for BoxStatefulTransformer<T, R>

Source§

impl<T, R> StatefulTransformer<T, R> for RcStatefulTransformer<T, R>

Source§

impl<T, R, F> StatefulTransformer<T, R> for F
where F: FnMut(T) -> R,