From 798fa623ea43b445a55ae5fa5a34b9716268a46d Mon Sep 17 00:00:00 2001 From: Ryan Pavlik Date: Fri, 17 Jan 2020 16:48:42 -0600 Subject: [PATCH] u_json: Add array helper. --- src/xrt/auxiliary/util/u_json.c | 41 ++++++++++++++++++++++++++++++++- src/xrt/auxiliary/util/u_json.h | 21 ++++++++++++++++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/src/xrt/auxiliary/util/u_json.c b/src/xrt/auxiliary/util/u_json.c index c92a721dc..2cda29e85 100644 --- a/src/xrt/auxiliary/util/u_json.c +++ b/src/xrt/auxiliary/util/u_json.c @@ -1,10 +1,49 @@ -// Copyright 2019, Collabora, Ltd. +// Copyright 2019-2020, Collabora, Ltd. // SPDX-License-Identifier: BSL-1.0 /*! * @file * @brief Tiny JSON wrapper around cJSON. * @author Jakob Bornecrantz + * @author Ryan Pavlik * @ingroup aux_util */ +#include "u_json.h" + #include "cjson/cJSON.c" + +size_t +u_json_get_double_array(const cJSON *json_array, + double *out_array, + size_t max_size) +{ + if (!json_array) { + return 0; + } + if (!out_array) { + return 0; + } + if (!cJSON_IsArray(json_array)) { + return 0; + } + if (max_size == 0) { + return 0; + } + size_t i = 0; + const cJSON *elt; + cJSON_ArrayForEach(elt, json_array) + { + if (!cJSON_IsNumber(elt)) { + fprintf(stderr, + "warning: u_json_get_double_array got a " + "non-number in a numeric array"); + return i; + } + out_array[i] = elt->valuedouble; + ++i; + if (i == max_size) { + break; + } + } + return i; +} diff --git a/src/xrt/auxiliary/util/u_json.h b/src/xrt/auxiliary/util/u_json.h index 3c2f232c4..11ae76be8 100644 --- a/src/xrt/auxiliary/util/u_json.h +++ b/src/xrt/auxiliary/util/u_json.h @@ -1,9 +1,10 @@ -// Copyright 2019, Collabora, Ltd. +// Copyright 2019-2020, Collabora, Ltd. // SPDX-License-Identifier: BSL-1.0 /*! * @file * @brief Tiny JSON wrapper around cJSON header. * @author Jakob Bornecrantz + * @author Ryan Pavlik * @ingroup aux_util */ @@ -12,3 +13,21 @@ #include "xrt/xrt_compiler.h" #include "cjson/cJSON.h" + + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/*! + * @brief Parse up to max_size doubles from a JSON array. + * + * @return the number of elements set. + */ +size_t +u_json_get_double_array(const cJSON *json_array, + double *out_array, + size_t max_size); +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus