pub fn use_state<T: Clone + Send + Sync + 'static>(
id: u64,
initial: T,
) -> (impl Fn() -> T, impl Fn(T)) {
let already_exists = load_system_state().get_component_state::<T>(id).is_some();
if !already_exists {
update_system_state(|s| {
let mut ns = s.clone();
ns.set_component_state(id, initial.clone());
ns
});
}
let getter = move || -> T {
load_system_state()
.get_component_state::<T>(id)
.map(|arc_lock| {
arc_lock
.read()
.ok()
.map(|guard| (*guard).clone())
.unwrap_or_else(|| initial.clone())
})
.unwrap_or_else(|| initial.clone())
};
let setter = {
move |value| {
update_system_state(|s| {
let mut ns = s.clone();
ns.set_component_state(id, value);
ns
});
}
};
(getter, setter)
}
pub fn use_state_hash(key: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut s = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut s);
s.finish()
}