[Date Prev][Date Next] [Chronological] [Thread] [Top]

Re: static assertions



Hallvard B Furuseth wrote:
I think we should insert a number of static assertions in the
OpenLDAP code: Asserts that fail or succeed at compile time.
E.g. for the comment in config.c:bindkey[] (ITS#6419).

Like this - in include/ac/assert.h?
Or ldap_cdefs.h in case we want to use it in installed headers?

/* Declaration which tries to force a compile error if !cond */
#define ber_static_assert(cond) \
     LBER_V(LDAP_CONST char) ber_assertion[ber_assertz(cond) + 1]

/* Return 0, or if !cond try to force a compile error */
#define ber_assertz(cond) (sizeof(struct { \
     int ber_assert1[(cond) ? 9 : -9], ber_assert2:(cond) ? 9 : -9; })&&  0)

/* Usage: */
ber_static_assert(~0U>= 0xFFFFFFFFUL);	/* int = 32 bits or wider */
int foo(int i) { return i + ber_assertz(LDAP_SUCCESS == 0); }

liblber will need a dummy variable 'const char ber_assertion[1];'.
We can drop that if anyone dislikes it: ber_static_assert() can take
an assertion_name parameter and declare a typedef based on that name.
Or it can generate a name from __LINE__.  Then we can have only one
static assert per line, which matters for macros but little else.

You could avoid the naming issue by just enclosing the body in a block {}. I'm assuming we only need this inside functions, and not at file scope.

Since this is all ber/LBER, it should go in an lber_* header file, not ac/assert.h.

--
  -- Howard Chu
  CTO, Symas Corp.           http://www.symas.com
  Director, Highland Sun     http://highlandsun.com/hyc/
  Chief Architect, OpenLDAP  http://www.openldap.org/project/