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
     1.1 --- a/src/cx/utils.h	Thu Feb 02 20:25:34 2023 +0100
     1.2 +++ b/src/cx/utils.h	Wed Feb 08 18:56:58 2023 +0100
     1.3 @@ -51,6 +51,15 @@
     1.4   */
     1.5  #define cx_for_n(varname, n) for (size_t varname = 0 ; (varname) < (n) ; (varname)++)
     1.6  
     1.7 +/**
     1.8 + * Convenience macro for swapping two pointers.
     1.9 + */
    1.10 +#ifdef __cplusplus
    1.11 +#define cx_swap_ptr(left, right) do {auto cx_tmp_swap_var = left; left = right; right = cx_tmp_swap_var;} while(0)
    1.12 +#else
    1.13 +#define cx_swap_ptr(left, right) do {void *cx_tmp_swap_var = left; left = right; right = cx_tmp_swap_var;} while(0)
    1.14 +#endif
    1.15 +
    1.16  // cx_szmul() definition
    1.17  
    1.18  #if (__GNUC__ >= 5 || defined(__clang__)) && !defined(CX_NO_SZMUL_BUILTIN)
     2.1 --- a/test/test_utils.cpp	Thu Feb 02 20:25:34 2023 +0100
     2.2 +++ b/test/test_utils.cpp	Wed Feb 08 18:56:58 2023 +0100
     2.3 @@ -39,6 +39,16 @@
     2.4      }
     2.5  }
     2.6  
     2.7 +TEST(Utils, swap_ptr) {
     2.8 +    int i = 5;
     2.9 +    int j = 8;
    2.10 +    int *ip = &i;
    2.11 +    int *jp = &j;
    2.12 +    cx_swap_ptr(ip, jp);
    2.13 +    EXPECT_EQ(ip, &j);
    2.14 +    EXPECT_EQ(jp, &i);
    2.15 +}
    2.16 +
    2.17  TEST(Utils, szmul) {
    2.18      size_t r;
    2.19      int e;

mercurial