add pointer swap utility

Wed, 08 Feb 2023 18:56:58 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 08 Feb 2023 18:56:58 +0100
changeset 646
dfd0403ff8b6
parent 645
ec50abb285ad
child 647
2e6e9d9f2159

add pointer swap utility

src/cx/utils.h file | annotate | diff | comparison | revisions
test/test_utils.cpp file | annotate | diff | comparison | revisions
--- a/src/cx/utils.h	Thu Feb 02 20:25:34 2023 +0100
+++ b/src/cx/utils.h	Wed Feb 08 18:56:58 2023 +0100
@@ -51,6 +51,15 @@
  */
 #define cx_for_n(varname, n) for (size_t varname = 0 ; (varname) < (n) ; (varname)++)
 
+/**
+ * Convenience macro for swapping two pointers.
+ */
+#ifdef __cplusplus
+#define cx_swap_ptr(left, right) do {auto cx_tmp_swap_var = left; left = right; right = cx_tmp_swap_var;} while(0)
+#else
+#define cx_swap_ptr(left, right) do {void *cx_tmp_swap_var = left; left = right; right = cx_tmp_swap_var;} while(0)
+#endif
+
 // cx_szmul() definition
 
 #if (__GNUC__ >= 5 || defined(__clang__)) && !defined(CX_NO_SZMUL_BUILTIN)
--- a/test/test_utils.cpp	Thu Feb 02 20:25:34 2023 +0100
+++ b/test/test_utils.cpp	Wed Feb 08 18:56:58 2023 +0100
@@ -39,6 +39,16 @@
     }
 }
 
+TEST(Utils, swap_ptr) {
+    int i = 5;
+    int j = 8;
+    int *ip = &i;
+    int *jp = &j;
+    cx_swap_ptr(ip, jp);
+    EXPECT_EQ(ip, &j);
+    EXPECT_EQ(jp, &i);
+}
+
 TEST(Utils, szmul) {
     size_t r;
     int e;

mercurial