summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaisuke Nojiri <dnojiri@chromium.org>2018-12-06 12:42:28 -0800
committerchrome-bot <chrome-bot@chromium.org>2018-12-10 16:00:33 -0800
commiteb3ac28cb5a634cf15770e1f79558cdfa4a6923b (patch)
tree2892c3dfcdf15e062b19b7a23a381c589f21363f
parent080075c076d9c3daabb050abfe9d71b55b585656 (diff)
downloadchrome-ec-eb3ac28cb5a634cf15770e1f79558cdfa4a6923b.tar.gz
util: Add macro to swap two variables
This patch adds swap(a,b), which swaps the values in two variables. It requires c99 for typeof. 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 an operator. Signed-off-by: Daisuke Nojiri <dnojiri@chromium.org> BUG=none BRANCH=none TEST=buildall Change-Id: Id656e173d372dfff759d9aee9314a008a6d91786 Reviewed-on: https://chromium-review.googlesource.com/1366306 Commit-Ready: Daisuke Nojiri <dnojiri@chromium.org> Tested-by: Daisuke Nojiri <dnojiri@chromium.org> Reviewed-by: Daisuke Nojiri <dnojiri@chromium.org>
-rw-r--r--include/util.h15
-rw-r--r--test/utils.c20
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();
}