Skip to content

Instantly share code, notes, and snippets.

@paulfrische
Created April 13, 2025 18:31
Show Gist options
  • Select an option

  • Save paulfrische/51e963395c94069d403cfd2c0b0c9262 to your computer and use it in GitHub Desktop.

Select an option

Save paulfrische/51e963395c94069d403cfd2c0b0c9262 to your computer and use it in GitHub Desktop.
personal version of lib.rs/anymap for fun and profit
#[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