intrepid_core/extract/
state.rs

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
use std::convert::Infallible;

use crate::{Context, Frame, StateNotReadyError};

use super::Extractor;

/// Retrieve the state an action expects. This has the side-effect of creating a
/// state dependency for the action. All actions in a given system must share the
/// same state type.
///
#[derive(Clone)]
pub struct State<T: Clone>(pub T);

impl<StateContents> Extractor<StateContents> for State<StateContents>
where
    StateContents: Clone + Send + Sync,
{
    type Error = StateNotReadyError;

    fn extract(_: Frame, context: &Context<StateContents>) -> Result<Self, Self::Error> {
        Ok(State(context.state()?))
    }
}

impl<State> Extractor<State> for () {
    type Error = Infallible;

    fn extract(_: Frame, _: &Context<State>) -> Result<Self, Self::Error> {
        Ok(())
    }
}

#[test]
fn extract_state_from_frame() {
    let state = 42;
    let frame = Frame::default();
    let context = Context::from(state);
    let extracted = State::extract(frame, &context).unwrap();

    assert_eq!(extracted.0, 42);
}