From f26f66d866ba1a9f3204e6fdfe2b07e67b5492ad Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 10 Apr 2024 21:41:32 +0200 Subject: Adding upstream version 2.8. Signed-off-by: Daniel Baumann --- util/json.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 util/json.c (limited to 'util/json.c') diff --git a/util/json.c b/util/json.c new file mode 100644 index 0000000..2de5848 --- /dev/null +++ b/util/json.c @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +#include +#include + +#include "json.h" +#include "types.h" + +struct json_object *util_json_object_new_double(long double d) +{ + struct json_object *obj; + char *str; + + if (asprintf(&str, "%Lf", d) < 0) + return NULL; + + obj = json_object_new_string(str); + + free(str); + return obj; + +} + +struct json_object *util_json_object_new_uint64(uint64_t i) +{ + struct json_object *obj; + char *str; + + if (asprintf(&str, "%" PRIu64, i) < 0) + return NULL; + + obj = json_object_new_string(str); + + free(str); + return obj; + +} + +static int util_json_object_string_to_number(struct json_object *jso, + struct printbuf *pb, int level, + int flags) +{ + ssize_t len = json_object_get_string_len(jso); + + printbuf_memappend(pb, json_object_get_string(jso), len); + + return 0; +} + +struct json_object *util_json_object_new_uint128(nvme_uint128_t val) +{ + struct json_object *obj; + + obj = json_object_new_string(uint128_t_to_string(val)); + json_object_set_serializer(obj, util_json_object_string_to_number, NULL, NULL); + + return obj; +} + +uint64_t util_json_object_get_uint64(struct json_object *obj) +{ + uint64_t val = 0; + + if (json_object_is_type(obj, json_type_string)) { + char *end = NULL; + const char *buf; + + buf = json_object_get_string(obj); + val = strtoull(buf, &end, 10); + if ((val == 0 && errno != 0) || (end == buf)) + return 0; + } + + return val; +} -- cgit v1.2.3