From 465d5d5649d3d81af80c7e00caf897eedd9f6ac1 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Sun, 16 Dec 2018 15:17:06 +1030 Subject: [PATCH] json: add json_to_bool() helper. Signed-off-by: Rusty Russell --- common/json.c | 16 ++++++++++++++++ common/json.h | 3 +++ common/json_tok.c | 13 ++----------- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/common/json.c b/common/json.c index 81e1aa06e..89a738446 100644 --- a/common/json.c +++ b/common/json.c @@ -2,6 +2,7 @@ #include "json.h" #include #include +#include #include #include #include @@ -111,6 +112,21 @@ bool json_to_int(const char *buffer, const jsmntok_t *tok, int *num) return true; } +bool json_to_bool(const char *buffer, const jsmntok_t *tok, bool *b) +{ + if (tok->type != JSMN_PRIMITIVE) + return false; + if (memeqstr(buffer + tok->start, tok->end - tok->start, "true")) { + *b = true; + return true; + } + if (memeqstr(buffer + tok->start, tok->end - tok->start, "false")) { + *b = false; + return true; + } + return false; +} + bool json_to_bitcoin_amount(const char *buffer, const jsmntok_t *tok, uint64_t *satoshi) { diff --git a/common/json.h b/common/json.h index 170af0420..a80d87858 100644 --- a/common/json.h +++ b/common/json.h @@ -40,6 +40,9 @@ bool json_to_double(const char *buffer, const jsmntok_t *tok, double *num); /* Extract signed integer from this (may be a string, or a number literal) */ bool json_to_int(const char *buffer, const jsmntok_t *tok, int *num); +/* Extract boolean from this */ +bool json_to_bool(const char *buffer, const jsmntok_t *tok, bool *b); + /* Extract satoshis from this (may be a string, or a decimal number literal) */ bool json_to_bitcoin_amount(const char *buffer, const jsmntok_t *tok, uint64_t *satoshi); diff --git a/common/json_tok.c b/common/json_tok.c index 6e2732216..b03be4d41 100644 --- a/common/json_tok.c +++ b/common/json_tok.c @@ -1,4 +1,3 @@ -#include #include #include #include @@ -25,16 +24,8 @@ bool json_tok_bool(struct command *cmd, const char *name, bool **b) { *b = tal(cmd, bool); - if (tok->type == JSMN_PRIMITIVE) { - if (memeqstr(buffer + tok->start, tok->end - tok->start, "true")) { - **b = true; - return true; - } - if (memeqstr(buffer + tok->start, tok->end - tok->start, "false")) { - **b = false; - return true; - } - } + if (json_to_bool(buffer, tok, *b)) + return true; command_fail(cmd, JSONRPC2_INVALID_PARAMS, "'%s' should be 'true' or 'false', not '%.*s'", name, tok->end - tok->start, buffer + tok->start);