Commits

Anonymous committed f9a42eb

Design: Added asserts in parser. Increased number of tokens in demo.

  • Participants
  • Parent commits b0e793d

Comments (0)

Files changed (2)

 
 #include "jsmn.h"
 
-#define NUM_TOKENS 20
+#define NUM_TOKENS 30
 
-static void json_dump_obj(jsontok_t *obj, const char *js) {
+static void jsmn_dump_obj(jsontok_t *obj, const char *js) {
 	size_t len;
 
 	if (obj->end < 0 || obj->start < 0) {
 
 	r = jsmn_parse((unsigned char *) js, tokens, NUM_TOKENS, &errpos);
 	if (r < 0) {
-		printf("error at pos %d: %s\n", errpos, &js[errpos]);
+		printf("error %d at pos %d: %s\n", r, errpos, &js[errpos]);
 		exit(EXIT_FAILURE);
 	}
 
 	for (i = 0; i<NUM_TOKENS; i++) {
-		json_dump_obj(&tokens[i], js);
+		jsmn_dump_obj(&tokens[i], js);
 	}
 
 	free(js);
 
 int jsmn_parse(const unsigned char *js, jsontok_t *tokens, size_t num_tokens, int *errpos) {
 
+#define jsmn_assert(cond, pos, err)	\
+	if (!(cond)) {	\
+		jsmn_error(&params, pos);	\
+		return (err);	\
+	}
+
 	struct jsmn_params params;
 
 	int r;
 			case '{': case '[':
 				type = (*p == '{' ? JSON_OBJECT : JSON_ARRAY);
 				cur_token = jsmn_token_start(&params, type, p - js);
+				jsmn_assert(cur_token != NULL, p - js, -1);
 				cur_token->start = p - js;
 				break;
 			case '}' : case ']':
 				type = (*p == '}' ? JSON_OBJECT : JSON_ARRAY);
 				cur_token = jsmn_token_end(&params, type, p - js + 1);
+				jsmn_assert(cur_token != NULL, p - js, -1);
 				cur_token->end = p - js + 1;
 				break;
 
 			case '5': case '6': case '7' : case '8': case '9':
 			case 't': case 'f': case 'n' :
 				cur_token = jsmn_token_start(&params, JSON_OTHER, p - js);
+				jsmn_assert(cur_token != NULL, p - js, -1);
 				r = jsmn_parse_primitive(js, cur_token);
-				if (r < 0) {
-					jsmn_error(&params, p - js);
-					return -1;
-				}
-				p = &js[cur_token->end];
+				jsmn_assert(r == 0, p - js, -2);
+				p = &js[cur_token->end] - 1;
 				break;
 
 			case '\"':
 				cur_token = jsmn_token_start(&params, JSON_STRING, p - js);
+				jsmn_assert(cur_token != NULL, p - js, -1);
 				r = jsmn_parse_string(js, cur_token);
-				if (r < 0) {
-					jsmn_error(&params, p - js);
-					return -1;
-				}
+				jsmn_assert(r == 0, p - js, -2);
 				p = &js[cur_token->end];
 				break;