Skip to main content

cloudillo_core/
extensions.rs

1//! Type-erased extension map for AppState
2//!
3//! Allows feature modules to register their own state without coupling
4//! the core AppState struct to feature-specific types.
5
6use std::any::{Any, TypeId};
7use std::collections::HashMap;
8
9pub struct Extensions {
10	map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
11}
12
13impl Extensions {
14	pub fn new() -> Self {
15		Self { map: HashMap::new() }
16	}
17
18	pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) {
19		self.map.insert(TypeId::of::<T>(), Box::new(val));
20	}
21
22	pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
23		self.map.get(&TypeId::of::<T>())?.downcast_ref::<T>()
24	}
25}
26
27impl Default for Extensions {
28	fn default() -> Self {
29		Self::new()
30	}
31}
32
33// vim: ts=4