From 6ae8cdeeb6c11658c684a19b536c83db8c14606c Mon Sep 17 00:00:00 2001 From: BevapDin Date: Sat, 28 Dec 2019 14:11:42 +0100 Subject: [PATCH 1/2] Refactor code in npc::wield to be safer: - Check result of `inventory::find_item` before using it. Using `INT_MIN` is safe (`inventory::find_item` will return a null item reference), but this is clearer. - Add assertions to catch future errors. - Compare item pointers, not names. --- src/npc.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/npc.cpp b/src/npc.cpp index 7e0ec9b6710d8..589dcc3d55b40 100644 --- a/src/npc.cpp +++ b/src/npc.cpp @@ -1159,9 +1159,13 @@ bool npc::wield( item &it ) // check if the item is in a holster int position = inv.position_by_item( &it ); - item &holster = inv.find_item( position ); - if( holster.tname() != it.tname() && holster.is_holster() && !holster.contents.empty() ) { - invoke_item( &holster ); + if( position != INT_MIN ) { + item &maybe_holster = inv.find_item( position ); + assert( !maybe_holster.is_null() ); + if( &maybe_holster != &it && maybe_holster.is_holster() ) { + assert( !maybe_holster.contents.empty() ); + invoke_item( &maybe_holster ); + } } moves -= 15; From 420fd68610ba7311ac3b3bdbc3821d342e0ab0c0 Mon Sep 17 00:00:00 2001 From: BevapDin Date: Sat, 28 Dec 2019 14:24:45 +0100 Subject: [PATCH 2/2] Stop process of wielding when the item has been taken from the holster. --- src/npc.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/npc.cpp b/src/npc.cpp index 589dcc3d55b40..aa6b058c1abfa 100644 --- a/src/npc.cpp +++ b/src/npc.cpp @@ -1164,7 +1164,14 @@ bool npc::wield( item &it ) assert( !maybe_holster.is_null() ); if( &maybe_holster != &it && maybe_holster.is_holster() ) { assert( !maybe_holster.contents.empty() ); + const size_t old_size = maybe_holster.contents.size(); invoke_item( &maybe_holster ); + // @TODO change invoke_item to somehow report this change + // Hacky: test whether wielding the item from the holster has been done. + // (Wielding may be prevented by various reasons: see player::wield_contained) + if( old_size != maybe_holster.contents.size() ) { + return true; + } } }