From c3a8d02b9f66763b3ef1756ba1dec4e9b039d14e Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Fri, 4 Aug 2023 19:49:57 +0200 Subject: [PATCH] must_be.h: Add must_be_array() macro MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit This macro statically asserts that the argument is an array. Link: Cc: Christian Göttsche Cc: Serge Hallyn Cc: Iker Pedrosa Signed-off-by: Alejandro Colomar --- lib/must_be.h | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/lib/must_be.h b/lib/must_be.h index 30edc558f..2ca7b62a2 100644 --- a/lib/must_be.h +++ b/lib/must_be.h @@ -58,4 +58,41 @@ ) +/* + * SYNOPSIS + * int must_be_array(a); + * + * ARGUMENTS + * a Array. + * + * DESCRIPTION + * This macro fails compilation if 'a' is not an array. It is + * useful in macros that accept an array as a parameter, where this + * macro can validate the macro argument. It prevent passing a + * pointer to such macros, which would otherwise produce silent + * bugs. + * + * RETURN VALUE + * 0 + * + * ERRORS + * If 'a' is not an array, the compilation will fail. + * + * EXAMPLES + * int a[10]; + * int *p; + * + * must_be_array(a); // Ok + * must_be_array(p); // Compile-time error + * + * SEE ALSO + * must_be() + */ + + +#define is_same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) +#define is_array(a) (!is_same_type((a), &(a)[0])) +#define must_be_array(a) must_be(is_array(a)) + + #endif // include guard -- 2.47.2