json: Support floating point values NaN and Infinity for numbers

Add support to decode the special floating point values NaN, Infinity
and -Infinity. For example:
  {"nan_val":NaN,"inf_pos":Infinity,"inf_neg":-Infinity}

Note that this commit is a preparation for the built-in support of
floating point values and these are only accepted when compiled with
the flag -DCONFIG_JSON_LIBRARY_FP_SUPPORT.

Signed-off-by: Christoph Winklhofer <cj.winklhofer@gmail.com>
This commit is contained in:
Christoph Winklhofer 2025-03-22 10:24:08 +01:00 committed by Benjamin Cabé
parent f07f2da8dc
commit c7b7ec2faf

View File

@ -212,6 +212,37 @@ static void *lexer_number(struct json_lexer *lex)
}
}
static void *lexer_number_nan(struct json_lexer *lex)
{
#ifdef CONFIG_JSON_LIBRARY_FP_SUPPORT
backup(lex);
switch (peek(lex)) {
case 'N':
if (!accept_run(lex, "NaN")) {
emit(lex, JSON_TOK_NUMBER);
return lexer_json;
}
break;
case 'I':
if (!accept_run(lex, "Infinity")) {
emit(lex, JSON_TOK_NUMBER);
return lexer_json;
}
break;
case '-':
if (!accept_run(lex, "-Infinity")) {
emit(lex, JSON_TOK_NUMBER);
return lexer_json;
}
break;
}
#endif
emit(lex, JSON_TOK_ERROR);
return NULL;
}
static void *lexer_json(struct json_lexer *lex)
{
while (true) {
@ -236,10 +267,16 @@ static void *lexer_json(struct json_lexer *lex)
case 't':
case 'f':
return lexer_boolean;
case 'N':
case 'I':
return lexer_number_nan;
case '-':
if (isdigit(peek(lex)) != 0) {
return lexer_number;
}
if (peek(lex) == 'I') {
return lexer_number_nan;
}
__fallthrough;
default: