1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use action::Action;
pub trait Reducer<T> {
fn process(&self, state: T, action: &Action) -> T;
}
impl<T> From<fn(T, &Action) -> T> for PureReducer<T> {
fn from(f: fn(T, &Action) -> T) -> PureReducer<T> {
PureReducer { f }
}
}
struct PureReducer<T> {
f: fn(T, &Action) -> T,
}
impl<T> Reducer<T> for PureReducer<T> {
fn process(&self, state: T, action: &Action) -> T {
(self.f)(state, action)
}
}
#[derive(Debug)]
pub struct LoggingReducer {}
impl<T> Reducer<T> for LoggingReducer {
fn process(&self, state: T, action: &Action) -> T {
println!("Processing {:?}", action);
state
}
}
#[cfg(test)]
mod tests {
use super::PureReducer;
use action::Action;
use state_machine::StateMachine;
fn pure_reducer_increment(x: u32, _a: &Action) -> u32 {
x + 1
}
#[test]
fn can_create_reducer_from_function() {
let r : PureReducer<u32> = PureReducer { f: pure_reducer_increment };
let mut sm = StateMachine::new(0);
sm.push_reducer(&r);
assert_eq!(sm.get_state(), 0);
sm.process(&Action::new("some_action", &[]));
assert_eq!(sm.get_state(), 1);
}
}