Skip to main content

cloudillo_core/
extensions.rs

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