Skip to content

Commit 7be7430

Browse files
committed
add MathLib::{addition,subtraction}WouldOverflow
1 parent 192c2ee commit 7be7430

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

‎lib/mathlib.cpp‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1369,3 +1369,17 @@ MathLib::value operator>>(const MathLib::value &v1, const MathLib::value &v2)
13691369
{
13701370
return v1.shiftRight(v2);
13711371
}
1372+
1373+
bool MathLib::additionWouldOverflow(MathLib::bigint x, MathLib::bigint y)
1374+
{
1375+
if (y > 0)
1376+
return x > std::numeric_limits<MathLib::bigint>::max() - y;
1377+
return std::numeric_limits<MathLib::bigint>::min() - y > x;
1378+
}
1379+
1380+
bool MathLib::subtractionWouldOverflow(MathLib::bigint x, MathLib::bigint y)
1381+
{
1382+
if (y == std::numeric_limits<MathLib::bigint>::min())
1383+
return x >= 0;
1384+
return additionWouldOverflow(x, -y);
1385+
}

‎lib/mathlib.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ class CPPCHECKLIB MathLib {
169169
static bool isOctalDigit(char c);
170170

171171
static unsigned int encodeMultiChar(const std::string& str);
172+
173+
static bool additionWouldOverflow(MathLib::bigint x, MathLib::bigint y);
174+
static bool subtractionWouldOverflow(MathLib::bigint x, MathLib::bigint y);
172175
};
173176

174177
MathLib::value operator+(const MathLib::value &v1, const MathLib::value &v2);

0 commit comments

Comments
 (0)