]> git.ipfire.org Git - thirdparty/kmod.git/commitdiff
Add macro to safely derive the size of an array
authorLucas De Marchi <lucas.demarchi@profusion.mobi>
Tue, 29 Nov 2011 19:59:58 +0000 (17:59 -0200)
committerLucas De Marchi <lucas.demarchi@profusion.mobi>
Tue, 29 Nov 2011 19:59:58 +0000 (17:59 -0200)
libkmod/macro.h

index 11e38a7eae472910bc72017ea5e27a27a34457da..d09d6645eb13aef3af621e6c1bab8611e52c7c9f 100644 (file)
         ((char *)(member_ptr) - offsetof(containing_type, member))     \
         - check_types_match(*(member_ptr), ((containing_type *)0)->member))
 
+/**
+ * BUILD_ASSERT_OR_ZERO - assert a build-time dependency, as an expression.
+ * @cond: the compile-time condition which must be true.
+ *
+ * Your compile will fail if the condition isn't true, or can't be evaluated
+ * by the compiler.  This can be used in an expression: its value is "0".
+ *
+ * Example:
+ *      #define foo_to_char(foo)                                            \
+ *              ((char *)(foo)                                              \
+ *              + BUILD_ASSERT_OR_ZERO(offsetof(struct foo, string) == 0))
+ */
+#define BUILD_ASSERT_OR_ZERO(cond) \
+        (sizeof(char [1 - 2*!(cond)]) - 1)
+
+/* Two gcc extensions.
+ * &a[0] degrades to a pointer: a different type from an array */
+#define _array_size_chk(arr)                                            \
+        BUILD_ASSERT_OR_ZERO(!__builtin_types_compatible_p(typeof(arr), \
+                                                        typeof(&(arr)[0])))
+
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + _array_size_chk(arr))
+
 /* Attributes */
 
 #define __must_check __attribute__((warn_unused_result))