]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
must_be.h: Add must_be_array() macro
authorAlejandro Colomar <alx@kernel.org>
Fri, 4 Aug 2023 17:49:57 +0000 (19:49 +0200)
committerIker Pedrosa <ikerpedrosam@gmail.com>
Fri, 1 Sep 2023 07:39:23 +0000 (09:39 +0200)
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>
lib/must_be.h

index 30edc558f5dc1554562648b77c42b22988ff2a49..2ca7b62a2851ed3c500b5734a4cec40183038f0b 100644 (file)
 )
 
 
+/*
+ * 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