diff options
author | MarcoFalke <falke.marco@gmail.com> | 2021-11-02 09:48:10 +0100 |
---|---|---|
committer | MarcoFalke <falke.marco@gmail.com> | 2021-12-17 10:46:39 +0100 |
commit | fac01888d17423d6c23a9ce15d98fc88fb34e3cc (patch) | |
tree | 9a53718485b5521f4fb2ee6458e5cbaacf8d5033 /src/test/util_tests.cpp | |
parent | fa526d8fb6ab8f2678a30d4536aa9c45218f5269 (diff) |
Move AdditionOverflow to util, Add CheckedAdd with unit tests
Diffstat (limited to 'src/test/util_tests.cpp')
-rw-r--r-- | src/test/util_tests.cpp | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/src/test/util_tests.cpp b/src/test/util_tests.cpp index 9540cead24..bc3ef9f7f1 100644 --- a/src/test/util_tests.cpp +++ b/src/test/util_tests.cpp @@ -15,6 +15,7 @@ #include <util/getuniquepath.h> #include <util/message.h> // For MessageSign(), MessageVerify(), MESSAGE_MAGIC #include <util/moneystr.h> +#include <util/overflow.h> #include <util/spanparsing.h> #include <util/strencodings.h> #include <util/string.h> @@ -1463,6 +1464,38 @@ BOOST_AUTO_TEST_CASE(test_IsDigit) BOOST_CHECK_EQUAL(IsDigit(9), false); } +/* Check for overflow */ +template <typename T> +static void TestAddMatrixOverflow() +{ + constexpr T MAXI{std::numeric_limits<T>::max()}; + BOOST_CHECK(!CheckedAdd(T{1}, MAXI)); + BOOST_CHECK(!CheckedAdd(MAXI, MAXI)); + BOOST_CHECK_EQUAL(0, CheckedAdd(T{0}, T{0}).value()); + BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{0}, MAXI).value()); + BOOST_CHECK_EQUAL(MAXI, CheckedAdd(T{1}, MAXI - 1).value()); +} + +/* Check for overflow or underflow */ +template <typename T> +static void TestAddMatrix() +{ + TestAddMatrixOverflow<T>(); + constexpr T MINI{std::numeric_limits<T>::min()}; + constexpr T MAXI{std::numeric_limits<T>::max()}; + BOOST_CHECK(!CheckedAdd(T{-1}, MINI)); + BOOST_CHECK(!CheckedAdd(MINI, MINI)); + BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{0}, MINI).value()); + BOOST_CHECK_EQUAL(MINI, CheckedAdd(T{-1}, MINI + 1).value()); + BOOST_CHECK_EQUAL(-1, CheckedAdd(MINI, MAXI).value()); +} + +BOOST_AUTO_TEST_CASE(util_overflow) +{ + TestAddMatrixOverflow<unsigned>(); + TestAddMatrix<signed>(); +} + BOOST_AUTO_TEST_CASE(test_ParseInt32) { int32_t n; |