Add json_boolean() macro

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.
This commit is contained in:
Petri Lehtinen 2012-07-30 07:20:36 +03:00
parent 52924288b9
commit b6a1d8cfd4
3 changed files with 28 additions and 2 deletions

View File

@ -255,8 +255,8 @@ returns an error status.
True, False and Null True, False and Null
==================== ====================
These values are implemented as singletons, so each of these functions These three values are implemented as singletons, so the returned
returns the same value each time. pointers won't change between invocations of these functions.
.. function:: json_t *json_true(void) .. function:: json_t *json_true(void)
@ -270,6 +270,15 @@ returns the same value each time.
Returns the JSON false value. 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) .. function:: json_t *json_null(void)
.. refcounting:: new .. refcounting:: new

View File

@ -86,6 +86,7 @@ json_t *json_integer(json_int_t value);
json_t *json_real(double value); json_t *json_real(double value);
json_t *json_true(void); json_t *json_true(void);
json_t *json_false(void); json_t *json_false(void);
#define json_boolean(val) ((val) ? json_true() : json_false())
json_t *json_null(void); json_t *json_null(void);
static JSON_INLINE static JSON_INLINE

View File

@ -14,6 +14,22 @@ static void run_tests()
{ {
json_t *value; 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); value = json_integer(1);
if(json_typeof(value) != JSON_INTEGER) if(json_typeof(value) != JSON_INTEGER)
fail("json_typeof failed"); fail("json_typeof failed");