1use std::any::{Any, TypeId, type_name};
2use std::collections::HashMap;
3
4use crate::{Focus, Keybindings, Pointer};
5
6pub struct World {
27 resources: HashMap<TypeId, Box<dyn Any>>,
28}
29
30impl Default for World {
31 fn default() -> Self {
32 let mut world = Self::new();
33 world.insert(Focus::default());
34 world.insert(Keybindings::new());
35 world.insert(Pointer::new());
36 world
37 }
38}
39
40impl World {
41 #[must_use]
42 pub fn new() -> Self {
43 Self {
44 resources: HashMap::new(),
45 }
46 }
47
48 pub fn insert<R: Any>(&mut self, res: R) {
49 self.resources.insert(TypeId::of::<R>(), Box::new(res));
50 }
51
52 #[must_use]
56 pub fn get<R: Any>(&self) -> &R {
57 self.try_get()
58 .unwrap_or_else(|| panic!("resource not found: {}", type_name::<R>()))
59 }
60
61 pub fn get_mut<R: Any>(&mut self) -> &mut R {
65 self.try_get_mut()
66 .unwrap_or_else(|| panic!("resource not found: {}", type_name::<R>()))
67 }
68
69 #[must_use]
70 pub fn try_get<R: Any>(&self) -> Option<&R> {
71 self.resources
72 .get(&TypeId::of::<R>())
73 .and_then(|b| b.downcast_ref())
74 }
75
76 pub fn try_get_mut<R: Any>(&mut self) -> Option<&mut R> {
77 self.resources
78 .get_mut(&TypeId::of::<R>())
79 .and_then(|b| b.downcast_mut())
80 }
81
82 #[must_use]
83 pub fn exists<R: Any>(&self) -> bool {
84 self.resources.contains_key(&TypeId::of::<R>())
85 }
86
87 pub fn remove<R: Any>(&mut self) -> Option<R> {
88 self.resources
89 .remove(&TypeId::of::<R>())
90 .and_then(|b| b.downcast().ok())
91 .map(|b| *b)
92 }
93}