Created
April 13, 2025 18:31
-
-
Save paulfrische/51e963395c94069d403cfd2c0b0c9262 to your computer and use it in GitHub Desktop.
personal version of lib.rs/anymap for fun and profit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #[derive(Debug, Default)] | |
| struct AnyMap { | |
| map: HashMap<TypeId, Box<dyn Any>>, | |
| } | |
| impl AnyMap { | |
| fn new() -> Self { | |
| Default::default() | |
| } | |
| // TODO: error handling | |
| fn insert<T: 'static>(&mut self, value: T) { | |
| let typeid = TypeId::of::<T>(); | |
| self.map.entry(typeid).or_insert(Box::new(value)); | |
| } | |
| fn get<T: 'static>(&self) -> Option<&T> { | |
| let typeid = TypeId::of::<T>(); | |
| self.map.get(&typeid)?.downcast_ref() | |
| } | |
| fn get_mut<T: 'static>(&mut self) -> Option<&mut T> { | |
| let typeid = TypeId::of::<T>(); | |
| self.map.get_mut(&typeid)?.downcast_mut() | |
| } | |
| fn remove<T: 'static>(&mut self) { | |
| let typeid = TypeId::of::<T>(); | |
| self.map.remove(&typeid); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment