From: Alejandro Colomar Date: Sun, 30 Jul 2023 12:12:45 +0000 (+0200) Subject: must_be.h: Add must_be() macro X-Git-Tag: 4.15.0-rc1~210 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=10f31a97e2b2d0de396702bce56ce9464c4cc4ac;p=thirdparty%2Fshadow.git must_be.h: Add must_be() macro It's like static_assert(3), but can be used in more places. It's necessary for writing a must_be_array() macro. Link: Cc: Christian Göttsche Cc: Serge Hallyn Cc: Iker Pedrosa Signed-off-by: Alejandro Colomar --- diff --git a/lib/Makefile.am b/lib/Makefile.am index 3b56ce4cf..3f749aa12 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -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 index 000000000..30edc558f --- /dev/null +++ b/lib/must_be.h @@ -0,0 +1,61 @@ +/* + * SPDX-FileCopyrightText: 2019-2023, Alejandro Colomar + * SPDX-License-Identifier: BSD-3-Clause + */ + + +#ifndef SHADOW_INCLUDE_LIBMISC_MUST_BE_H_ +#define SHADOW_INCLUDE_LIBMISC_MUST_BE_H_ + + +#include + +#include + + +/* + * 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