From: Timo Sirainen Date: Wed, 2 Jul 2014 17:13:35 +0000 (+0300) Subject: lib: Added UINT64_SUM_OVERFLOWS() X-Git-Tag: 2.2.14.rc1~306 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=cbc01fc844fa307e565cc81fd78536d7afca05a9;p=thirdparty%2Fdovecot%2Fcore.git lib: Added UINT64_SUM_OVERFLOWS() Maybe the unit tests are kind of unnecessary since the macro is so simple, but at least it's now a well tested simple macro :) --- diff --git a/src/lib/bits.h b/src/lib/bits.h index 528152a064..5c6b768d71 100644 --- a/src/lib/bits.h +++ b/src/lib/bits.h @@ -12,6 +12,9 @@ #include #include +#define UINT64_SUM_OVERFLOWS(a, b) \ + (a > (uint64_t)-1 - b) + size_t nearest_power(size_t num) ATTR_CONST; unsigned int bits_required8(uint8_t num) ATTR_CONST; diff --git a/src/lib/test-bits.c b/src/lib/test-bits.c index 67ecb58405..46f2054398 100644 --- a/src/lib/test-bits.c +++ b/src/lib/test-bits.c @@ -60,8 +60,32 @@ static void test_bits_requiredXX(void) test_end(); } +static void test_sum_overflows(void) +{ +#define MAX64 (uint64_t)-1 + static const struct { + uint64_t a, b; + bool overflows; + } tests[] = { + { MAX64-1, 1, FALSE }, + { MAX64, 1, TRUE }, + { MAX64-1, 1, FALSE }, + { MAX64-1, 2, TRUE }, + { MAX64-1, MAX64-1, TRUE }, + { MAX64-1, MAX64, TRUE }, + { MAX64, MAX64, TRUE } + }; + unsigned int i; + + test_begin("UINT64_SUM_OVERFLOWS"); + for (i = 0; i < N_ELEMENTS(tests); i++) + test_assert(UINT64_SUM_OVERFLOWS(tests[i].a, tests[i].b) == tests[i].overflows); + test_end(); +} + void test_bits() { test_nearest_power(); test_bits_requiredXX(); + test_sum_overflows(); }