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 :)
#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;
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();
}