|
9 | 9 | #include <errno.h> |
10 | 10 | #include <limits.h> |
11 | 11 | #include <sys/printk.h> |
| 12 | +#include <stdio.h> |
12 | 13 | #include <sys/util.h> |
13 | 14 | #include <stdbool.h> |
14 | 15 | #include <stdlib.h> |
@@ -790,6 +791,57 @@ static int num_encode(const int32_t *num, json_append_bytes_t append_bytes, |
790 | 791 | return append_bytes(buf, (size_t)ret, data); |
791 | 792 | } |
792 | 793 |
|
| 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 | + |
793 | 845 | static int bool_encode(const bool *value, json_append_bytes_t append_bytes, |
794 | 846 | void *data) |
795 | 847 | { |
@@ -820,6 +872,12 @@ static int encode(const struct json_obj_descr *descr, const void *val, |
820 | 872 | ptr, append_bytes, data); |
821 | 873 | case JSON_TOK_NUMBER: |
822 | 874 | 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); |
823 | 881 | default: |
824 | 882 | return -EINVAL; |
825 | 883 | } |
|
0 commit comments