must_be.h: Add must_be_array() macro

This macro statically asserts that the argument is an array.

Link: <https://stackoverflow.com/a/57537491>
Cc: Christian Göttsche <cgzones@googlemail.com>
Cc: Serge Hallyn <serge@hallyn.com>
Cc: Iker Pedrosa <ipedrosa@redhat.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
This commit is contained in:
Alejandro Colomar
2023-08-04 19:49:57 +02:00
committed by Iker Pedrosa
parent 10f31a97e2
commit c3a8d02b9f

View File

@@ -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