From 29ee29b3887773e36fb7ad55ab44392dae7f8412 Mon Sep 17 00:00:00 2001 From: HampusM Date: Wed, 20 Aug 2025 17:09:08 +0200 Subject: feat(ecs): add funcs for getting target comp of wildcard pairs --- ecs/src/component.rs | 57 +++++++++++++++++++++++----------------------------- 1 file changed, 25 insertions(+), 32 deletions(-) (limited to 'ecs/src/component.rs') diff --git a/ecs/src/component.rs b/ecs/src/component.rs index 6fb1230..3c2112e 100644 --- a/ecs/src/component.rs +++ b/ecs/src/component.rs @@ -81,31 +81,25 @@ impl<'comp, ComponentData: 'static> Handle<'comp, ComponentData> /// # Errors /// Will return `Err` if acquiring the component's lock fails. pub fn from_entity_component_ref( - entity_component_ref: EntityComponentRef<'comp>, + entity_component_ref: &EntityComponentRef<'comp>, ) -> Result { - Ok(Self::new( + Self::new( entity_component_ref .component() .read_nonblock() .map_err(AcquireLockError)?, - )) + ) } - pub(crate) fn new(inner: ReadGuard<'comp, Box>) -> Self + fn new(inner: ReadGuard<'comp, Box>) -> Result { - Self { - inner: inner.map(|component| { - component - .downcast_ref::() - .unwrap_or_else(|| { - panic!( - "Failed to downcast component to type {}", - type_name::() - ); - }) - }), - } + Ok(Self { + inner: ReadGuard::try_map(inner, |component| { + component.downcast_ref::() + }) + .map_err(|_| HandleError::IncorrectType)?, + }) } } @@ -132,31 +126,27 @@ impl<'comp, ComponentData: 'static> HandleMut<'comp, ComponentData> /// # Errors /// Will return `Err` if acquiring the component's lock fails. pub fn from_entity_component_ref( - entity_component_ref: EntityComponentRef<'comp>, + entity_component_ref: &EntityComponentRef<'comp>, ) -> Result { - Ok(Self::new( + Self::new( entity_component_ref .component() .write_nonblock() .map_err(AcquireLockError)?, - )) + ) } - pub(crate) fn new(inner: WriteGuard<'comp, Box>) -> Self + // TODO: Make this function private + pub(crate) fn new(inner: WriteGuard<'comp, Box>) + -> Result { - Self { - inner: inner.map(|component| { - component - .downcast_mut::() - .unwrap_or_else(|| { - panic!( - "Failed to downcast component to type {}", - type_name::() - ); - }) - }), - } + Ok(Self { + inner: WriteGuard::try_map(inner, |component| { + component.downcast_mut::() + }) + .map_err(|_| HandleError::IncorrectType)?, + }) } } @@ -183,6 +173,9 @@ pub enum HandleError { #[error(transparent)] AcquireLockFailed(#[from] AcquireLockError), + + #[error("Incorrect component type")] + IncorrectType, } #[derive(Debug, thiserror::Error)] -- cgit v1.2.3-18-g5258