Browse Source

cppmagic: Conditionals

Implement CPPMAGIC_IFELSE which operates similar to the C ? : operator, but
is evaluated at preprocessing time.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
David Gibson 10 years ago
parent
commit
395a2f8413
2 changed files with 19 additions and 1 deletions
  1. 14 0
      ccan/cppmagic/cppmagic.h
  2. 5 1
      ccan/cppmagic/test/run.c

+ 14 - 0
ccan/cppmagic/cppmagic.h

@@ -84,4 +84,18 @@
 #define CPPMAGIC_ISEMPTY(...)		\
 	CPPMAGIC_ISZERO(CPPMAGIC_NONEMPTY(__VA_ARGS__))
 
+/*
+ * CPPMAGIC_IFELSE - preprocessor conditional
+ *
+ * CPPMAGIC_IFELSE(@cond)(@if)(@else)
+ *	expands to @else if @cond is '0', otherwise expands to @if
+ */
+#define _CPPMAGIC_IF_0(...)		_CPPMAGIC_IF_0_ELSE
+#define _CPPMAGIC_IF_1(...)		__VA_ARGS__ _CPPMAGIC_IF_1_ELSE
+#define _CPPMAGIC_IF_0_ELSE(...)	__VA_ARGS__
+#define _CPPMAGIC_IF_1_ELSE(...)
+#define _CPPMAGIC_IFELSE(cond_)		CPPMAGIC_GLUE2(_CPPMAGIC_IF_, cond_)
+#define CPPMAGIC_IFELSE(cond_)		\
+	_CPPMAGIC_IFELSE(CPPMAGIC_NONZERO(cond_))
+
 #endif /* CCAN_CPPMAGIC_H */

+ 5 - 1
ccan/cppmagic/test/run.c

@@ -17,7 +17,7 @@ static inline void check1(const char *orig, const char *expand,
 
 int main(void)
 {
-	plan_tests(21);
+	plan_tests(24);
 
 	CHECK1(CPPMAGIC_NOTHING(), "");
 	CHECK1(CPPMAGIC_GLUE2(a, b), "ab");
@@ -47,6 +47,10 @@ int main(void)
 	CHECK1(CPPMAGIC_ISEMPTY(0), "0");
 	CHECK1(CPPMAGIC_ISEMPTY(a, b, c), "0");
 	
+	CHECK1(CPPMAGIC_IFELSE(0)(abc)(def), "def");
+	CHECK1(CPPMAGIC_IFELSE(1)(abc)(def), "abc");
+	CHECK1(CPPMAGIC_IFELSE(not zero)(abc)(def), "abc");
+
 	/* This exits depending on whether all tests passed */
 	return exit_status();
 }