diff --git a/ferretro_components/src/base/mod.rs b/ferretro_components/src/base/mod.rs index f464c2c..96f6693 100644 --- a/ferretro_components/src/base/mod.rs +++ b/ferretro_components/src/base/mod.rs @@ -143,11 +143,21 @@ impl RetroComponentBase { Ok(RetroComponentId(self.components.len() - 1)) } + pub fn component_ref(&self, id: RetroComponentId) -> Result<&T> { + self.component_ptr(id) + .map(|x| unsafe { &*x }) + } + pub fn component_mut(&mut self, id: RetroComponentId) -> Result<&mut T> { + self.component_ptr(id) + .map(|x| unsafe { &mut *x }) + } + + fn component_ptr(&self, id: RetroComponentId) -> Result<*mut T> { let (comp_type, comp_ptr) = self.component_ptrs.get(id.0) .ok_or_else(|| format!("Invalid ID given to component_mut: {:?}", id))?; if *comp_type == TypeId::of::() { - Ok(unsafe { &mut *(*comp_ptr as *mut T) }) + Ok(*comp_ptr as *mut T) } else { Err(format!( "Invalid downcast for {:?}: {:?} != {:?}",