json: json_to_int helper.

Plugins need this for decoding the error code, for example (we only
had unsigned handling).

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
This commit is contained in:
Rusty Russell 2018-12-16 15:16:06 +10:30
parent 22ca896b54
commit 024b1a8d54
2 changed files with 26 additions and 0 deletions

View File

@ -88,6 +88,29 @@ bool json_to_number(const char *buffer, const jsmntok_t *tok,
return true;
}
bool json_to_int(const char *buffer, const jsmntok_t *tok, int *num)
{
char *end;
long l;
l = strtol(buffer + tok->start, &end, 0);
if (end != buffer + tok->end)
return false;
BUILD_ASSERT(sizeof(l) >= sizeof(*num));
*num = l;
/* Check for overflow/underflow */
if ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE)
return false;
/* Check for truncation */
if (*num != l)
return false;
return true;
}
bool json_to_bitcoin_amount(const char *buffer, const jsmntok_t *tok,
uint64_t *satoshi)
{

View File

@ -37,6 +37,9 @@ bool json_to_u64(const char *buffer, const jsmntok_t *tok,
/* Extract double from this (must be a number literal) */
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 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);