diff options
author | Ahmad Fatoum <a.fatoum@pengutronix.de> | 2023-09-21 12:24:24 +0200 |
---|---|---|
committer | Sascha Hauer <s.hauer@pengutronix.de> | 2023-09-22 11:43:16 +0200 |
commit | e25184ba656d0b7e2a5b04aeae0e65a838beaff5 (patch) | |
tree | 41ea697e54cb75d87036369a34d367b68eb3418b /lib | |
parent | 0c8bd55b08a47493f6cde8a5ad9ca291fc262e6c (diff) | |
download | barebox-e25184ba656d0b7e2a5b04aeae0e65a838beaff5.tar.gz barebox-e25184ba656d0b7e2a5b04aeae0e65a838beaff5.tar.xz |
lib: jsmn: add helper for allocating tokens
jsmn_parse can be called with a NULL buffer to determine the needed
allocation size beforehand. Most users will go on to dynamically
allocate that buffer, so add a helper that does just that and start
using it to simplify the json selftest.
Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
Link: https://lore.barebox.org/20230921102426.1109289-2-a.fatoum@pengutronix.de
Signed-off-by: Sascha Hauer <s.hauer@pengutronix.de>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/jsmn.c | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/lib/jsmn.c b/lib/jsmn.c index 9eeed790d9..3d2ada7b7f 100644 --- a/lib/jsmn.c +++ b/lib/jsmn.c @@ -370,6 +370,42 @@ JSMN_API void jsmn_init(jsmn_parser *parser) { parser->toksuper = -1; } +/** + * Parse JSON string and fill tokens into self-allocated buffer. + */ +JSMN_API jsmntok_t *jsmn_parse_alloc(const char *js, const size_t len, + unsigned int *num_tokens) +{ + + ssize_t token_count; + jsmn_parser parser; + jsmntok_t *tokens; + int ret; + + jsmn_init(&parser); + + /* Figure out how many tokens we need. */ + ret = jsmn_parse(&parser, js, len, NULL, 0); + if (ret < 0) + return NULL; + + token_count = ret; + + tokens = kmalloc_array(token_count, sizeof(jsmntok_t), GFP_KERNEL); + if (!tokens) + return NULL; + + jsmn_init(&parser); + ret = jsmn_parse(&parser, js, len, tokens, token_count); + if (ret < 0) { + free(tokens); + return NULL; + } + + if (num_tokens) + *num_tokens = ret; + return tokens; +} JSMN_API bool jsmn_eq(const char *val, const char *json, const jsmntok_t *token) { size_t token_size = jsmn_token_size(token); |