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
//! Reducers
//! Stateless functions used by the state machine to process actions.
//! Each action will be fed to a reducer if it is
//! binded with the `StateMachine` that received this action.

use action::Action;

/// core logic trait, any structure that implement this trait
/// can be used to manipulate state.
pub trait Reducer<T> {
    /// Take the ownership of the state, and return the state after application of the action
    fn process(&self, state: T, action: &Action) -> T;
}

impl<T> From<fn(T, &Action) -> T> for PureReducer<T> {
    /// Create a pure reducer from a compatible function
    fn from(f: fn(T, &Action) -> T) -> PureReducer<T> {
        PureReducer { f }
    }
}

/// Wrapper to use a pure function as a reducer
struct PureReducer<T> {
    /// Function to be called when reducing
    f: fn(T, &Action) -> T,
}

impl<T> Reducer<T> for PureReducer<T> {
    /// Call the reducer function
    fn process(&self, state: T, action: &Action) -> T {
        (self.f)(state, action)
    }
}

/// `LoggingReducer`
/// Print the category of each action received
/// Leave the state unchanged
#[derive(Debug)]
pub struct LoggingReducer {}

impl<T> Reducer<T> for LoggingReducer {
    /// Print the action and give back state ownership
    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);
    }

}