Skip to content

Commit 7bc0e02

Browse files
committed
lib: json: Add NUM64, FLOAT & DOUBLE
1 parent 0ca6d24 commit 7bc0e02

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

include/data/json.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ enum json_tokens {
4343
JSON_TOK_COLON = ':',
4444
JSON_TOK_COMMA = ',',
4545
JSON_TOK_NUMBER = '0',
46+
JSON_TOK_NUMBER64 = '1',
47+
JSON_TOK_FLOAT = '2',
48+
JSON_TOK_DOUBLE = '3',
4649
JSON_TOK_TRUE = 't',
4750
JSON_TOK_FALSE = 'f',
4851
JSON_TOK_NULL = 'n',

lib/os/json.c

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <errno.h>
1010
#include <limits.h>
1111
#include <sys/printk.h>
12+
#include <stdio.h>
1213
#include <sys/util.h>
1314
#include <stdbool.h>
1415
#include <stdlib.h>
@@ -790,6 +791,57 @@ static int num_encode(const int32_t *num, json_append_bytes_t append_bytes,
790791
return append_bytes(buf, (size_t)ret, data);
791792
}
792793

794+
static int num64_encode(const int64_t *num, json_append_bytes_t append_bytes,
795+
void *data)
796+
{
797+
char buf[3 * sizeof(int64_t)];
798+
int ret;
799+
800+
ret = snprintk(buf, sizeof(buf), "%lld", *num);
801+
if (ret < 0) {
802+
return ret;
803+
}
804+
if (ret >= (int)sizeof(buf)) {
805+
return -ENOMEM;
806+
}
807+
808+
return append_bytes(buf, (size_t)ret, data);
809+
}
810+
811+
static int float_encode(const float *num, const uint8_t dp, json_append_bytes_t append_bytes,
812+
void *data)
813+
{
814+
char buf[3 * sizeof(float)];
815+
int ret;
816+
817+
ret = sprintf(buf, "%.3f", *num);
818+
if (ret < 0) {
819+
return ret;
820+
}
821+
if (ret >= (int)sizeof(buf)) {
822+
return -ENOMEM;
823+
}
824+
825+
return append_bytes(buf, (size_t)ret, data);
826+
}
827+
828+
static int double_encode(const double *num, const uint8_t dp, json_append_bytes_t append_bytes,
829+
void *data)
830+
{
831+
char buf[3 * sizeof(double)];
832+
int ret;
833+
834+
ret = sprintf(buf, "%.7f", *num);
835+
if (ret < 0) {
836+
return ret;
837+
}
838+
if (ret >= (int)sizeof(buf)) {
839+
return -ENOMEM;
840+
}
841+
842+
return append_bytes(buf, (size_t)ret, data);
843+
}
844+
793845
static int bool_encode(const bool *value, json_append_bytes_t append_bytes,
794846
void *data)
795847
{
@@ -820,6 +872,12 @@ static int encode(const struct json_obj_descr *descr, const void *val,
820872
ptr, append_bytes, data);
821873
case JSON_TOK_NUMBER:
822874
return num_encode(ptr, append_bytes, data);
875+
case JSON_TOK_NUMBER64:
876+
return num64_encode(ptr, append_bytes, data);
877+
case JSON_TOK_FLOAT:
878+
return float_encode(ptr, 3, append_bytes, data);
879+
case JSON_TOK_DOUBLE:
880+
return double_encode(ptr, 7, append_bytes, data);
823881
default:
824882
return -EINVAL;
825883
}

0 commit comments

Comments
 (0)