From 285a0b2b01b3b9fd641310f66fde9aad4424afc6 Mon Sep 17 00:00:00 2001 From: Joshua Barretto Date: Mon, 16 Oct 2023 09:53:15 +0000 Subject: [PATCH] Fixed potential panic when adding dead pet --- common/src/comp/group.rs | 46 +++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/common/src/comp/group.rs b/common/src/comp/group.rs index dd63a45710..390cc4e7a0 100644 --- a/common/src/comp/group.rs +++ b/common/src/comp/group.rs @@ -264,27 +264,35 @@ impl GroupManager { uids: &Uids, notifier: &mut impl FnMut(specs::Entity, ChangeNotification), ) { - let group = match groups.get(owner).copied() { - Some(group) => group, - None => { - let new_group = self.create_group(owner, 1); - groups.insert(owner, new_group).unwrap(); - // Inform - notifier(owner, ChangeNotification::NewLeader(owner)); - new_group - }, - }; + if !entities.is_alive(owner) { + warn!("Tried to create new pet for non-existent owner {owner:?}"); + } else if !entities.is_alive(pet) { + warn!("Tried to create new pet for non-existent pet {pet:?}"); + } else { + let group = match groups.get(owner).copied() { + Some(group) => group, + None => { + let new_group = self.create_group(owner, 1); + // Unwrap can't fail, we checked that `owner` is alive above + groups.insert(owner, new_group).unwrap(); + // Inform + notifier(owner, ChangeNotification::NewLeader(owner)); + new_group + }, + }; - // Inform - members(group, &*groups, entities, alignments, uids).for_each(|(e, role)| match role { - Role::Member => { - notifier(e, ChangeNotification::Added(pet, Role::Pet)); - }, - Role::Pet => {}, - }); + // Inform + members(group, &*groups, entities, alignments, uids).for_each(|(e, role)| match role { + Role::Member => { + notifier(e, ChangeNotification::Added(pet, Role::Pet)); + }, + Role::Pet => {}, + }); - // Add - groups.insert(pet, group).unwrap(); + // Add + // Unwrap can't fail, we checked that `pet` is alive above + groups.insert(pet, group).unwrap(); + } } pub fn leave_group(