macro_rules! stateful_processor {
($struct_name:ident, $state_type:ty, $type:ty, $process_fn:expr) => { ... };
($struct_name:ident, $state_type:ty, $state_value:expr, $type:ty, $process_fn:expr) => { ... };
}Expand description
Creates a stateful processor that maintains its own internal state.
This macro generates a struct that implements StatefulProcessor<T>. The processing logic
can read and modify the internal state during its operation.
Two variants are available:
- Takes a state type and requires the state to be provided via a
new()constructor. - Takes a state type and an initial value expression, providing a
new()constructor with no arguments.
§Arms
§1. With new(state) constructor
$struct_name: Name of the processor struct.$state_type: Type of the internal state.$type: Type of the data to be processed.$process_fn: A closure|state, data| -> new_data.
§2. With new() constructor and initial state
$struct_name: Name of the processor struct.$state_type: Type of the internal state.$state_value: An expression that evaluates to the initial state.$type: Type of the data to be processed.$process_fn: A closure|state, data| -> new_data.
§Examples
§1. With new(state)
use type_flow_macros::stateful_processor;
use type_flow_traits::StatefulProcessor;
// A processor that adds a configurable number to the input.
stateful_processor!(AddN, i32, i32, |state: &mut i32, data: i32| {
data + *state
});
let mut processor = AddN::new(5); // State is 5
assert_eq!(processor.process(10), 15);
assert_eq!(processor.process(20), 25); // State remains 5§2. With initial state value
use type_flow_macros::stateful_processor;
use type_flow_traits::StatefulProcessor;
// A processor that accumulates values.
stateful_processor!(Accumulator, i32, 0, i32, |state: &mut i32, data: i32| {
*state += data;
*state // returns the new accumulated value
});
let mut processor = Accumulator::new();
assert_eq!(processor.process(5), 5);
assert_eq!(processor.process(10), 15);
assert_eq!(processor.process(-3), 12);