Add json_boolean() macro
authorPetri Lehtinen <petri@digip.org>
Mon, 30 Jul 2012 04:20:36 +0000 (07:20 +0300)
committerPetri Lehtinen <petri@digip.org>
Mon, 30 Jul 2012 04:20:37 +0000 (07:20 +0300)
Mostly for symmetry reasons. Makes it easier e.g. to:

  int ok = 0;
  if(something)
      ok = 1;

  json_object_set_new(obj, "ok", json_boolean(ok));

Fixes #86.

doc/apiref.rst
src/jansson.h
test/suites/api/test_simple.c

index b0a120f..fd27e38 100644 (file)
@@ -255,8 +255,8 @@ returns an error status.
 True, False and Null
 ====================
 
-These values are implemented as singletons, so each of these functions
-returns the same value each time.
+These three values are implemented as singletons, so the returned
+pointers won't change between invocations of these functions.
 
 .. function:: json_t *json_true(void)
 
@@ -270,6 +270,15 @@ returns the same value each time.
 
    Returns the JSON false value.
 
+.. function:: json_t *json_boolean(val)
+
+   .. refcounting:: new
+
+   Returns JSON false if ``val`` is zero, and JSON true otherwise.
+   This is a macro, and equivalent to ``val ? json_true() :
+   json_false()``.
+
+
 .. function:: json_t *json_null(void)
 
    .. refcounting:: new
index 966ceeb..1f1cc14 100644 (file)
@@ -86,6 +86,7 @@ json_t *json_integer(json_int_t value);
 json_t *json_real(double value);
 json_t *json_true(void);
 json_t *json_false(void);
+#define json_boolean(val)      ((val) ? json_true() : json_false())
 json_t *json_null(void);
 
 static JSON_INLINE
index dc8c8dd..4e2bb2f 100644 (file)
@@ -14,6 +14,22 @@ static void run_tests()
 {
     json_t *value;
 
+    value = json_boolean(1);
+    if(!json_is_true(value))
+        fail("json_boolean(1) failed");
+    json_decref(value);
+
+    value = json_boolean(-123);
+    if(!json_is_true(value))
+        fail("json_boolean(-123) failed");
+    json_decref(value);
+
+    value = json_boolean(0);
+    if(!json_is_false(value))
+        fail("json_boolean(0) failed");
+    json_decref(value);
+
+
     value = json_integer(1);
     if(json_typeof(value) != JSON_INTEGER)
         fail("json_typeof failed");