add a non-mut version, component_ref

This commit is contained in:
lifning 2021-10-17 21:56:53 -07:00
parent 268f1b4ff8
commit f1a9f7dd23
1 changed files with 11 additions and 1 deletions

View File

@ -143,11 +143,21 @@ impl RetroComponentBase {
Ok(RetroComponentId(self.components.len() - 1))
}
pub fn component_ref<T: RetroComponent>(&self, id: RetroComponentId) -> Result<&T> {
self.component_ptr(id)
.map(|x| unsafe { &*x })
}
pub fn component_mut<T: RetroComponent>(&mut self, id: RetroComponentId) -> Result<&mut T> {
self.component_ptr(id)
.map(|x| unsafe { &mut *x })
}
fn component_ptr<T: RetroComponent>(&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::<T>() {
Ok(unsafe { &mut *(*comp_ptr as *mut T) })
Ok(*comp_ptr as *mut T)
} else {
Err(format!(
"Invalid downcast for {:?}: {:?} != {:?}",