add SWAP macro

Add a macro for exchanging the values of variables. It allows users to avoid repetition and takes care of the temporary variable for them. It also makes sure that the storage sizes of its two parameters are the same. Its memcpy(1) calls are optimized away by current compilers. Also add a conservative semantic patch for transforming only swaps of variables of the same type. Signed-off-by: Rene Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed Jan 28, 2017 at 22:38 UTC 568edcb95a8b86ffd0d267b124896df8ea81307c
2 files changed +38
contrib/coccinelle/swap.cocci new
+28
@@ -0,0 +1,28 @@
1 +@ swap_with_declaration @
2 +type T;
3 +identifier tmp;
4 +T a, b;
5 +@@
6 +- T tmp = a;
7 ++ T tmp;
8 ++ tmp = a;
9 + a = b;
10 + b = tmp;
11 +
12 +@ swap @
13 +type T;
14 +T tmp, a, b;
15 +@@
16 +- tmp = a;
17 +- a = b;
18 +- b = tmp;
19 ++ SWAP(a, b);
20 +
21 +@ extends swap @
22 +identifier unused;
23 +@@
24 + {
25 + ...
26 +- T unused;
27 + ... when != unused
28 + }
git-compat-util.h
+10
@@ -527,6 +527,16 @@ static inline int ends_with(const char *str, const char *suffix)
527 return strip_suffix(str, suffix, &len);
528 }
529
530 +#define SWAP(a, b) do { \
531 + void *_swap_a_ptr = &(a); \
532 + void *_swap_b_ptr = &(b); \
533 + unsigned char _swap_buffer[sizeof(a)]; \
534 + memcpy(_swap_buffer, _swap_a_ptr, sizeof(a)); \
535 + memcpy(_swap_a_ptr, _swap_b_ptr, sizeof(a) + \
536 + BUILD_ASSERT_OR_ZERO(sizeof(a) == sizeof(b))); \
537 + memcpy(_swap_b_ptr, _swap_buffer, sizeof(a)); \
538 +} while (0)
539 +
540 #if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
541
542 #ifndef PROT_READ