From eb9a6c4a1ef46ea408a60a9320438cf7c1b9bb11 Mon Sep 17 00:00:00 2001 From: Heng Li Date: Sat, 29 Nov 2014 12:37:57 -0500 Subject: [PATCH] added API documentation --- kson.c | 11 +++++------ kson.h | 14 +++++++++++++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/kson.c b/kson.c index a3e08f8..ddf9822 100644 --- a/kson.c +++ b/kson.c @@ -4,7 +4,7 @@ #include #include "kson.h" -kson_node_t *kson_parse_core(const char *json, int *_n, int *error, const char **end) +kson_node_t *kson_parse(const char *json, int *_n, int *error, int *parsed_len) { int *stack = 0, top = 0, max = 0, n_a = 0, m_a = 0; kson_node_t *a = 0, *u; @@ -80,13 +80,13 @@ kson_node_t *kson_parse_core(const char *json, int *_n, int *error, const char * for (q = p; *q && *q != ']' && *q != '}' && *q != ',' && *q != ':'; ++q) if (*q == '\\') ++q; } - u->v.str = malloc(q - p + 1); strncpy(u->v.str, p, q - p); u->v.str[q-p] = 0; // equivalent to u->v.str=strndup(p, q-p) + u->v.str = (char*)malloc(q - p + 1); strncpy(u->v.str, p, q - p); u->v.str[q-p] = 0; // equivalent to u->v.str=strndup(p, q-p) u->type = c == '\''? KSON_TYPE_SGL_QUOTE : c == '"'? KSON_TYPE_DBL_QUOTE : KSON_TYPE_NO_QUOTE; p = c == '\'' || c == '"'? q : q - 1; } } while (*p && isblank(*p)) ++p; // skip trailing blanks - *end = p; + if (parsed_len) *parsed_len = p - json; if (top != 1) *error = KSON_ERR_EXTRA_LEFT; free(stack); @@ -121,9 +121,8 @@ void kson_print_recur(kson_node_t *nodes, kson_node_t *p) int main(int argc, char *argv[]) { kson_node_t *nodes; - int n_nodes, error; - const char *end; - nodes = kson_parse_core("{'a' : 1, 'b':[0,'isn\\'t',true],'d':[{}]}", &n_nodes, &error, &end); + int n_nodes, error, parsed_len; + nodes = kson_parse("{'a' : 1, 'b':[0,'isn\\'t',true],'d':[{}]}", &n_nodes, &error, &parsed_len); if (error == 0) { kson_print_recur(nodes, &nodes[0]); putchar('\n'); diff --git a/kson.h b/kson.h index adefa4b..737c354 100644 --- a/kson.h +++ b/kson.h @@ -9,6 +9,7 @@ #define KSON_TYPE_BRACKET 4 #define KSON_TYPE_BRACE 5 +#define KSON_OK 0 #define KSON_ERR_EXTRA_LEFT 1 #define KSON_ERR_EXTRA_RIGHT 2 #define KSON_ERR_NO_KEY 3 @@ -26,7 +27,18 @@ typedef struct { extern "C" { #endif - kson_node_t *kson_parse_core(const char *json, int *_n, int *error, const char **end); + /** + * Parse a JSON string + * + * @param json JSON string + * @param n number of nodes + * @param error 0 if no error; or set to one of KSON_ERR_* values + * @param parsed_len if not NULL, equal to the parsed length + * + * @return An array of size $n keeping parsed nodes + */ + kson_node_t *kson_parse(const char *json, int *n, int *error, int *parsed_len); + void kson_print_recur(kson_node_t *nodes, kson_node_t *root); #ifdef __cplusplus -- 2.47.3