diff options
-rw-r--r-- | include/util.h | 15 | ||||
-rw-r--r-- | test/utils.c | 20 |
2 files changed, 35 insertions, 0 deletions
diff --git a/include/util.h b/include/util.h index 5c2a7f38a6..aa15ba4fa8 100644 --- a/include/util.h +++ b/include/util.h @@ -62,7 +62,22 @@ extern "C" { #define DIV_ROUND_UP(x, y) (((x) + ((y) - 1)) / (y)) #define DIV_ROUND_NEAREST(x, y) (((x) + ((y) / 2)) / (y)) +/* + * Swap two variables (requires c99) + * + * Swapping composites (e.g. a+b, x++) doesn't make sense. So, <a> and <b> + * can only be a variable (x) or a pointer reference (*x) without operator. + */ +#define swap(a, b) \ + do { \ + typeof(a) __t__; \ + __t__ = a; \ + a = b; \ + b = __t__; \ + } while (0) + #ifndef HIDE_EC_STDLIB + /* Standard library functions */ __stdlib_compat int atoi(const char *nptr); __stdlib_compat int isdigit(int c); diff --git a/test/utils.c b/test/utils.c index 08a3511d77..37122b49c9 100644 --- a/test/utils.c +++ b/test/utils.c @@ -386,6 +386,25 @@ static int test_mula32(void) return EC_SUCCESS; } +#define SWAP_TEST_HARNESS(t, x, y) \ + do { \ + t a = x, b = y; \ + swap(a, b); \ + TEST_ASSERT(a == y); \ + TEST_ASSERT(b == x); \ + } while (0) + + +static int test_swap(void) +{ + SWAP_TEST_HARNESS(uint8_t, UINT8_MAX, 0); + SWAP_TEST_HARNESS(uint16_t, UINT16_MAX, 0); + SWAP_TEST_HARNESS(uint32_t, UINT32_MAX, 0); + SWAP_TEST_HARNESS(float, 1, 0); + SWAP_TEST_HARNESS(double, 1, 0); + return EC_SUCCESS; +} + void run_test(void) { test_reset(); @@ -402,6 +421,7 @@ void run_test(void) RUN_TEST(test_scratchpad); RUN_TEST(test_cond_t); RUN_TEST(test_mula32); + RUN_TEST(test_swap); test_print_result(); } |