pub trait State: 'static {
    fn get_raw(&self, ty: TypeId) -> Option<&dyn Any>;
    fn get_mut_raw(&mut self, ty: TypeId) -> Option<&mut dyn Any>;
}
Expand description

A service provider pattern implementation = associated read-only container with type as a key.

Useful for building complex systems with callbacks without generic parameters.

Examples

mod call_back {
    use dyn_context::State;

    pub struct CallBack {
        callback: Option<fn(state: &mut dyn State)>
    }

    impl CallBack {
        pub fn new() -> Self { CallBack { callback: None } }

        pub fn set_callback(&mut self, callback: fn(state: &mut dyn State)) {
            self.callback.replace(callback);
        }

        pub fn call_back(&self, state: &mut dyn State) {
            self.callback.map(|callback| callback(state));
        }
    }
}

use call_back::CallBack;
use dyn_context::{SelfState, StateExt};
use std::convert::Into;

struct PrintState {
     value: String
}

impl SelfState for PrintState { }

let mut call_back = CallBack::new();
call_back.set_callback(|state| {
    let print: &PrintState = state.get();
    println!("{}", &print.value);
});
call_back.call_back(&mut PrintState { value: "Hello, world!".into() });

For using &str instead of String the free_lifetimes! macro can be used:

use call_back::CallBack;
use dyn_context::free_lifetimes;
use dyn_context::{SelfState, StateExt};

free_lifetimes! {
    struct PrintState {
        value: 'value ref str
    }
}

impl SelfState for PrintState { }

let mut call_back = CallBack::new();
call_back.set_callback(|state| {
    let print: &PrintState = state.get();
    println!("{}", print.value());
});
PrintStateBuilder {
    value: "Hello, world!"
}.build_and_then(|state| call_back.call_back(state));

Required Methods

Borrows shareable data entry.

Prefer high-level get wrap.

Borrows mutable data entry.

Prefer high-level get_mut wrap.

Trait Implementations

Merges two states into one and calls provided function with the combined state.

Merges two states into one and calls provided function with the combined state.

Implementations on Foreign Types

Implementors