From f1a9f7dd23833528eefa822931b1727ec0df9f1f Mon Sep 17 00:00:00 2001 From: lifning <> Date: Sun, 17 Oct 2021 21:56:53 -0700 Subject: [PATCH] add a non-mut version, component_ref --- ferretro_components/src/base/mod.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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 {:?}: {:?} != {:?}",