Skip to main content

tui_world/
world.rs

1use std::any::{Any, TypeId, type_name};
2use std::collections::HashMap;
3
4use crate::{Focus, Keybindings, Pointer};
5
6/// A type-safe container for storing and retrieving resources by their type.
7///
8/// `World` acts as a central storage for application state, allowing you to insert,
9/// retrieve, and remove resources of any type. Each type can only have one instance
10/// stored at a time.
11///
12/// By default, `World` is initialized with [`Focus`], [`Keybindings`], and [`Pointer`]
13/// resources.
14///
15/// # Example
16///
17/// ```ignore
18/// let mut world = World::default();
19///
20/// // Insert a custom resource
21/// world.insert(MyAppState::new());
22///
23/// // Retrieve it later
24/// let state = world.get::<MyAppState>();
25/// ```
26pub 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    /// # Panics
53    ///
54    /// Panics if the resource of type `R` is not found.
55    #[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    /// # Panics
62    ///
63    /// Panics if the resource of type `R` is not found.
64    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}