From 9589ea02402875b2dc8d0391c29975bc911765b7 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 30 Jan 2023 16:54:16 +1030 Subject: [PATCH] common: add routine to get double from JSON. I don't like it, but we do expose some times like this :( Signed-off-by: Rusty Russell --- common/json_parse_simple.c | 16 ++++++++++++++++ common/json_parse_simple.h | 3 +++ 2 files changed, 19 insertions(+) diff --git a/common/json_parse_simple.c b/common/json_parse_simple.c index 236c89bef..0ccbd9573 100644 --- a/common/json_parse_simple.c +++ b/common/json_parse_simple.c @@ -101,6 +101,22 @@ bool json_str_to_u64(const char *buffer, const jsmntok_t *tok, u64 *num) return json_to_u64(buffer, &temp, num); } +bool json_to_double(const char *buffer, const jsmntok_t *tok, double *num) +{ + char *end; + + errno = 0; + *num = strtod(buffer + tok->start, &end); + if (end != buffer + tok->end) + return false; + + /* Check for overflow */ + if (errno == ERANGE) + return false; + + return true; +} + bool json_to_u32(const char *buffer, const jsmntok_t *tok, u32 *num) { uint64_t u64; diff --git a/common/json_parse_simple.h b/common/json_parse_simple.h index 697dd4bad..2c7c3c897 100644 --- a/common/json_parse_simple.h +++ b/common/json_parse_simple.h @@ -42,6 +42,9 @@ bool json_str_to_u64(const char *buffer, const jsmntok_t *tok, u64 *num); /* Extract number from this (may be a string, or a number literal) */ bool json_to_u32(const char *buffer, const jsmntok_t *tok, u32 *num); +/* Extract double from this (generally a bad idea!) */ +bool json_to_double(const char *buffer, const jsmntok_t *tok, double *num); + /* Extract boolean from this */ bool json_to_bool(const char *buffer, const jsmntok_t *tok, bool *b);