]> git.ipfire.org Git - thirdparty/dovecot/core.git/commitdiff
lib: Added UINT64_SUM_OVERFLOWS()
authorTimo Sirainen <tss@iki.fi>
Wed, 2 Jul 2014 17:13:35 +0000 (20:13 +0300)
committerTimo Sirainen <tss@iki.fi>
Wed, 2 Jul 2014 17:13:35 +0000 (20:13 +0300)
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 :)

src/lib/bits.h
src/lib/test-bits.c

index 528152a064076406d50e53947f0241335c290e4d..5c6b768d716ab22a6fd83569eb83a4a50d82a957 100644 (file)
@@ -12,6 +12,9 @@
 #include <stddef.h>
 #include <stdint.h>
 
+#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;
index 67ecb58405fe201db4361d98d3417bd9b8bbee1a..46f20543980a3c4899c4a3e6372c0762afecae12 100644 (file)
@@ -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();
 }