From e9eef31344594926f726a63f5b5d48890ce4a4e5 Mon Sep 17 00:00:00 2001 From: myk002 Date: Thu, 19 Aug 2021 19:51:25 -0700 Subject: [PATCH] refactor list item removal into a library fn --- library/include/MiscUtils.h | 21 +++++++++++++++++++++ library/modules/Items.cpp | 21 +++++---------------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/library/include/MiscUtils.h b/library/include/MiscUtils.h index 4249abeef..7a5f050a2 100644 --- a/library/include/MiscUtils.h +++ b/library/include/MiscUtils.h @@ -310,6 +310,27 @@ Link *linked_list_insert_after(Link *pos, Link *link) return link; } +/** + * Returns true if the item with id idToRemove was found, deleted, and removed + * from the list. Otherwise returns false. + */ +template +bool linked_list_remove(Link *head, int32_t idToRemove) +{ + for (Link *link = head; link; link = link->next) + { + if (!link->item || link->item->id != idToRemove) + continue; + + link->prev->next = link->next; + if (link->next) + link->next->prev = link->prev; + delete(link); + return true; + } + return false; +} + template inline typename T::mapped_type map_find( const T &map, const typename T::key_type &key, diff --git a/library/modules/Items.cpp b/library/modules/Items.cpp index b4f551270..d3693aad7 100644 --- a/library/modules/Items.cpp +++ b/library/modules/Items.cpp @@ -832,23 +832,12 @@ static bool detachItem(MapExtras::MapCache &mc, df::item *item) } if (auto *ref = - virtual_cast(Items::getGeneralRef(item, general_ref_type::PROJECTILE))) + virtual_cast( + Items::getGeneralRef(item, general_ref_type::PROJECTILE))) { - int32_t proj_id = ((df::general_ref_projectile *)ref)->projectile_id; - df::proj_list_link *link = world->proj_list.next; - for (; link; link = link->next) - { - if (link->item->id != proj_id) - continue; - - link->prev->next = link->next; - if (link->next) - link->next->prev = link->prev; - delete(link); - break; - } - return DFHack::removeRef(item->general_refs, - general_ref_type::PROJECTILE, ref->getID()); + return linked_list_remove(&world->proj_list, ref->projectile_id) && + DFHack::removeRef(item->general_refs, + general_ref_type::PROJECTILE, ref->getID()); } if (item->flags.bits.on_ground)