diff --git a/common/json.c b/common/json.c index f3993e370..549e5445f 100644 --- a/common/json.c +++ b/common/json.c @@ -216,3 +216,69 @@ again: return toks; } + +const char *jsmntype_to_string(jsmntype_t t) +{ + switch (t) { + case JSMN_UNDEFINED : + return "UNDEFINED"; + case JSMN_OBJECT : + return "OBJECT"; + case JSMN_ARRAY : + return "ARRAY"; + case JSMN_STRING : + return "STRING"; + case JSMN_PRIMITIVE : + return "PRIMITIVE"; + } + return "INVALID"; +} + +void json_tok_print(const char *buffer, const jsmntok_t *tok) +{ + const jsmntok_t *first = tok; + const jsmntok_t *last = json_next(tok); + printf("size: %d, count: %td\n", tok->size, last - first); + while (first != last) { + printf("%td. %.*s, %s\n", first - tok, + first->end - first->start, buffer + first->start, + jsmntype_to_string(first->type)); + first++; + } + printf("\n"); +} + +jsmntok_t *json_tok_copy(const tal_t *ctx, const jsmntok_t *tok) +{ + const jsmntok_t *first = tok; + const jsmntok_t *last = json_next(tok); + + if (!tok) + return NULL; + jsmntok_t *arr = tal_arr(ctx, jsmntok_t, last - first); + jsmntok_t *dest = arr; + while (first != last) + *dest++ = *first++; + + return arr; +} + +void json_tok_remove(jsmntok_t **tokens, jsmntok_t *tok, size_t num) +{ + assert(*tokens); + assert((*tokens)->type == JSMN_ARRAY || (*tokens)->type == JSMN_OBJECT); + const jsmntok_t *src = tok; + const jsmntok_t *end = json_next(*tokens); + jsmntok_t *dest = tok; + int remove_count; + + for (int i = 0; i < num; i++) + src = json_next(src); + + remove_count = src - tok; + + memmove(dest, src, sizeof(jsmntok_t) * (end - src)); + + tal_resize(tokens, tal_count(*tokens) - remove_count); + (*tokens)->size -= num; +} diff --git a/common/json.h b/common/json.h index e27929a29..38120ea15 100644 --- a/common/json.h +++ b/common/json.h @@ -57,4 +57,19 @@ const jsmntok_t *json_get_arr(const jsmntok_t tok[], size_t index); /* If input is complete and valid, return tokens. */ jsmntok_t *json_parse_input(const char *input, int len, bool *valid); +/* Convert a jsmntype_t enum to a human readable string. */ +const char *jsmntype_to_string(jsmntype_t t); + +/* Print a json value for debugging purposes. */ +void json_tok_print(const char *buffer, const jsmntok_t *params); + +/* Return a copy of a json value as an array. */ +jsmntok_t *json_tok_copy(const tal_t *ctx, const jsmntok_t *tok); + +/* + * Remove @num json values from a json array or object. @tok points + * to the first value to remove. The array will be resized. + */ +void json_tok_remove(jsmntok_t **tokens, jsmntok_t *tok, size_t num); + #endif /* LIGHTNING_COMMON_JSON_H */