redux_rs/
selector.rs

1/// # Selector trait
2/// Selectors are the way to get the current state and transform it into something useful for our app.
3/// You can write a selector by implementing the `Selector` trait or by writing a function with the signature `Fn(&State) -> Result`
4///
5/// ## Trait example
6/// ```
7/// use redux_rs::Selector;
8///
9/// enum State {
10///     Authorized { bearer_token: String },
11///     Unauthorized
12/// }
13///
14/// struct BearerTokenSelector;
15/// impl Selector<State> for BearerTokenSelector {
16///     type Result = Option<String>;
17///
18///     fn select(&self, state: &State) -> Self::Result {
19///         match state {
20///             State::Authorized { bearer_token } => Some(bearer_token.clone()),
21///             State::Unauthorized => None
22///         }
23///     }
24/// }
25///
26/// let selector = BearerTokenSelector;
27/// let state = State::Authorized { bearer_token: "secret".to_string() };
28/// assert_eq!(selector.select(&state), Some("secret".to_string()));
29/// ```
30///
31/// ## Fn example
32/// ```
33/// use redux_rs::Selector;
34///
35/// enum State {
36///     Authorized { bearer_token: String },
37///     Unauthorized
38/// }
39///
40/// struct BearerTokenSelector;
41/// impl Selector<State> for BearerTokenSelector {
42///     type Result = Option<String>;
43///
44///     fn select(&self, state: &State) -> Self::Result {
45///         match state {
46///             State::Authorized { bearer_token } => Some(bearer_token.clone()),
47///             State::Unauthorized => None
48///         }
49///     }
50/// }
51///
52/// let selector = |state: &State| {
53///     match state {
54///         State::Authorized { bearer_token } => Some(bearer_token.clone()),
55///         State::Unauthorized => None
56///     }
57/// };
58/// let state = State::Authorized { bearer_token: "secret".to_string() };
59/// assert_eq!(selector.select(&state), Some("secret".to_string()));
60/// ```
61pub trait Selector<State> {
62    type Result;
63
64    fn select(&self, state: &State) -> Self::Result;
65}
66
67impl<F, State, Result> Selector<State> for F
68where
69    F: Fn(&State) -> Result,
70{
71    type Result = Result;
72
73    fn select(&self, state: &State) -> Self::Result {
74        self(state)
75    }
76}