[PATCH RFC bpf-next 48/52] libbpf: compress Endianness ops with a macro

From: Alexander Lobakin
Date: Tue Jun 28 2022 - 15:55:29 EST


All of the Endianness helpers for BPF programs have the same
pattern and can be defined using a compression macro, which
will also protect against typos and copy-paste mistakes.
Not speaking of saving locs, of course.
Ahh, if we only could define macros inside other macros.

Signed-off-by: Alexander Lobakin <alexandr.lobakin@xxxxxxxxx>
---
tools/lib/bpf/bpf_endian.h | 26 +++++++++-----------------
1 file changed, 9 insertions(+), 17 deletions(-)

diff --git a/tools/lib/bpf/bpf_endian.h b/tools/lib/bpf/bpf_endian.h
index ec9db4feca9f..b03db6aa3f14 100644
--- a/tools/lib/bpf/bpf_endian.h
+++ b/tools/lib/bpf/bpf_endian.h
@@ -77,23 +77,15 @@
# error "Fix your compiler's __BYTE_ORDER__?!"
#endif

-#define bpf_htons(x) \
+#define __bpf_endop(op, x) \
(__builtin_constant_p(x) ? \
- __bpf_constant_htons(x) : __bpf_htons(x))
-#define bpf_ntohs(x) \
- (__builtin_constant_p(x) ? \
- __bpf_constant_ntohs(x) : __bpf_ntohs(x))
-#define bpf_htonl(x) \
- (__builtin_constant_p(x) ? \
- __bpf_constant_htonl(x) : __bpf_htonl(x))
-#define bpf_ntohl(x) \
- (__builtin_constant_p(x) ? \
- __bpf_constant_ntohl(x) : __bpf_ntohl(x))
-#define bpf_cpu_to_be64(x) \
- (__builtin_constant_p(x) ? \
- __bpf_constant_cpu_to_be64(x) : __bpf_cpu_to_be64(x))
-#define bpf_be64_to_cpu(x) \
- (__builtin_constant_p(x) ? \
- __bpf_constant_be64_to_cpu(x) : __bpf_be64_to_cpu(x))
+ __bpf_constant_##op(x) : __bpf_##op(x))
+
+#define bpf_htons(x) __bpf_endop(htons, x)
+#define bpf_ntohs(x) __bpf_endop(ntohs, x)
+#define bpf_htonl(x) __bpf_endop(htonl, x)
+#define bpf_ntohl(x) __bpf_endop(ntohl, x)
+#define bpf_cpu_to_be64(x) __bpf_endop(cpu_to_be64, x)
+#define bpf_be64_to_cpu(x) __bpf_endop(be64_to_cpu, x)

#endif /* __BPF_ENDIAN__ */
--
2.36.1