From 01608064f2d3f64ce8d791a167a3a4e35cfc7235 Mon Sep 17 00:00:00 2001 From: Nat Quayle Nelson Date: Thu, 8 May 2025 17:51:23 -0500 Subject: [PATCH] DRY overflow-aware short addition --- src/game/boe.specials.cpp | 4 +--- src/mathutil.hpp | 7 +++++++ src/universe/creature.cpp | 4 +--- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/game/boe.specials.cpp b/src/game/boe.specials.cpp index 6b2e4eba..78498e51 100644 --- a/src/game/boe.specials.cpp +++ b/src/game/boe.specials.cpp @@ -1483,9 +1483,7 @@ short damage_monst(cCreature& victim, short who_hit, short how_much, eDamageType // Absorb damage? if((dam_type == eDamageType::FIRE || dam_type == eDamageType::MAGIC || dam_type == eDamageType::COLD) && victim.abil[eMonstAbil::ABSORB_SPELLS].active && get_ran(1,1,1000) <= victim.abil[eMonstAbil::ABSORB_SPELLS].special.extra1) { - if(32767 - victim.health > how_much) - victim.health = 32767; - else victim.health += how_much; + add_check_overflow(victim.health, how_much); ASB(" Magic absorbed."); return false; } diff --git a/src/mathutil.hpp b/src/mathutil.hpp index 211b7c47..adda983f 100644 --- a/src/mathutil.hpp +++ b/src/mathutil.hpp @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include @@ -46,3 +47,9 @@ template inline T sgn(T val) { return val == 0 ? 0 : std::copysign(1, val); } + +inline void add_check_overflow(short& val, int how_much) { + if(SHRT_MAX - val > how_much) + val = SHRT_MAX; + else val += how_much; +} \ No newline at end of file diff --git a/src/universe/creature.cpp b/src/universe/creature.cpp index 1c4b2cfd..d76ad559 100644 --- a/src/universe/creature.cpp +++ b/src/universe/creature.cpp @@ -302,9 +302,7 @@ int cCreature::magic_adjust(int how_much) { if(how_much <= 0) return how_much; if(abil[eMonstAbil::ABSORB_SPELLS].active && get_ran(1,1,1000) <= abil[eMonstAbil::ABSORB_SPELLS].special.extra1) { int gain = abil[eMonstAbil::ABSORB_SPELLS].special.extra2; - if(32767 - health > gain) - health = 32767; - else health += gain; + add_check_overflow(health, gain); return 0; } // TODO: Magic resistance status effect?