Skip to content

Commit e76ba7a

Browse files
moidxpamaury
authored andcommitted
[ujson] Add support for quoted integers.
This change implements parsed for quoted integers. The implementation authored by [email protected]. JSON messages generated by protobuf libraries will use quoted strings for `uint64` types. See for example: {"wafer_auth_secret":[2790285947,1491553456,2694274708,1137231153,1404344500,190480117,3248928340,4233979174],"test_unlock_token_hash":["18123448053906926503","14479932172051545263"],"test_exit_token_hash":["895855566562726762","1749132506438826860"]} The change provided in this patch allows the device to parse the payload above. Before this change, the ujson module would return a parsing integer error. Signed-off-by: Miguel Osorio <[email protected]> (cherry picked from commit d31761b)
1 parent 0b859cf commit e76ba7a

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

sw/device/lib/ujson/ujson.c

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,15 @@ status_t ujson_parse_qs(ujson_t *uj, char *str, size_t len) {
169169
status_t ujson_parse_integer(ujson_t *uj, void *result, size_t rsz) {
170170
char ch = (char)TRY(consume_whitespace(uj));
171171
bool neg = false;
172+
bool quoted = false;
173+
174+
if (ch == '"') {
175+
// If we encounter a quote while parsing an integer, assume that
176+
// the quoted string will contain an integer. Get the next
177+
// character and continue parsing as if we expect an integer.
178+
quoted = true;
179+
ch = (char)TRY(ujson_getc(uj));
180+
}
172181

173182
if (ch == '-') {
174183
neg = true;
@@ -194,8 +203,19 @@ status_t ujson_parse_integer(ujson_t *uj, void *result, size_t rsz) {
194203
break;
195204
ch = (char)s.value;
196205
}
197-
if (status_ok(s))
198-
TRY(ujson_ungetc(uj, ch));
206+
207+
if (status_ok(s)) {
208+
if (quoted) {
209+
if (ch != '"') {
210+
return INVALID_ARGUMENT();
211+
}
212+
// Close quote on an integer in quoted string.
213+
// Don't have to unget the quote because we
214+
// want to consume it.
215+
} else {
216+
TRY(ujson_ungetc(uj, ch));
217+
}
218+
}
199219

200220
if (neg) {
201221
if (value > (uint64_t)INT64_MAX + 1) {

sw/device/lib/ujson/ujson_test.cc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ TEST(UJson, ParseInteger) {
141141
INT(uint8_t, "256", 0);
142142
// This value overflows int64 and becomes its own negative.
143143
INT(int64_t, "9223372036854775808", -9223372036854775808);
144+
// Quoted number.
145+
INT(uint32_t, "\"123\"", 123);
144146
}
145147
#undef INT
146148
#undef SIMPLE_INT

0 commit comments

Comments
 (0)