]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
must_be.h: Add must_be() macro
authorAlejandro Colomar <alx@kernel.org>
Sun, 30 Jul 2023 12:12:45 +0000 (14:12 +0200)
committerIker Pedrosa <ikerpedrosam@gmail.com>
Fri, 1 Sep 2023 07:39:23 +0000 (09:39 +0200)
It's like static_assert(3), but can be used in more places.  It's
necessary for writing a must_be_array() macro.

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/Makefile.am
lib/must_be.h [new file with mode: 0644]

index 3b56ce4cfc7a68ea43fbdd960a50addc01d49318..3f749aa12bd8d3111f3cdebb43caec68c982ae8f 100644 (file)
@@ -88,6 +88,7 @@ libshadow_la_SOURCES = \
        memzero.c \
        memzero.h \
        motd.c \
+       must_be.h \
        myname.c \
        nss.c \
        nscd.c \
diff --git a/lib/must_be.h b/lib/must_be.h
new file mode 100644 (file)
index 0000000..30edc55
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * SPDX-FileCopyrightText: 2019-2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+
+#ifndef SHADOW_INCLUDE_LIBMISC_MUST_BE_H_
+#define SHADOW_INCLUDE_LIBMISC_MUST_BE_H_
+
+
+#include <config.h>
+
+#include <assert.h>
+
+
+/*
+ * SYNOPSIS
+ *     int must_be(bool e);
+ *
+ * ARGUMENTS
+ *     e       Expression to be asserted.
+ *
+ * DESCRIPTION
+ *     This macro fails compilation if 'e' is false.  If 'e' is true,
+ *     it returns (int) 0, so it doesn't affect the expression in which
+ *     it is contained.
+ *
+ *     This macro is similar to static_assert(3).  While
+ *     static_assert(3) can only be used where a statement is allowed,
+ *     this must_be() macro can be used wherever an expression is
+ *     allowed.
+ *
+ * RETURN VALUE
+ *     0
+ *
+ * ERRORS
+ *     If 'e' is false, the compilation will fail, as when using
+ *     static_assert(3).
+ *
+ * EXAMPLES
+ *     #define must_be_array(a)  must_be(is_array(a))
+ *
+ *     #define NITEMS(a)  (sizeof(a) / sizeof(*(a)) + must_be_array(a))
+ *
+ *     int foo[42];
+ *     int bar[NITEMS(foo)];
+ */
+
+
+#define must_be(e)                                                            \
+(                                                                             \
+       0 * (int) sizeof(                                                     \
+               struct {                                                      \
+                       static_assert(e, "");                                 \
+                       int ISO_C_forbids_a_struct_with_no_members_;          \
+               }                                                             \
+       )                                                                     \
+)
+
+
+#endif  // include guard