Skip to main content

sword_core/state/
traits.rs

1use crate::{DependencyInjectionError, State};
2use std::sync::Arc;
3
4pub trait FromState: Sized {
5    fn from_state(state: &State) -> Result<Self, DependencyInjectionError>;
6}
7
8pub trait FromStateArc: Sized {
9    fn from_state_arc(state: &State) -> Result<Self, DependencyInjectionError>;
10}
11
12// Implement FromState for T (uses .get() which clones the value)
13impl<T> FromState for T
14where
15    T: Clone + Send + Sync + 'static,
16{
17    fn from_state(state: &State) -> Result<Self, DependencyInjectionError> {
18        state.get::<T>()
19    }
20}
21
22// Implement FromStateArc for Arc<T> (uses .borrow() which returns Arc)
23impl<T> FromStateArc for Arc<T>
24where
25    T: Send + Sync + 'static,
26{
27    fn from_state_arc(state: &State) -> Result<Self, DependencyInjectionError> {
28        state.borrow::<T>()
29    }
30}