From a983a7606136a3dfd538a9940c5ebf48d200251c Mon Sep 17 00:00:00 2001 From: "Serge A. Zaitsev" Date: Thu, 2 Feb 2012 13:15:22 +0200 Subject: [PATCH] added reading with small number of tokens test, fixed NOMEM issue #2 --- jsmn.c | 8 ++++++-- jsmn_test.c | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/jsmn.c b/jsmn.c index cca3bbc..ef53cc0 100644 --- a/jsmn.c +++ b/jsmn.c @@ -60,8 +60,10 @@ static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, found: token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) + if (token == NULL) { + parser->pos = start; return JSMN_ERROR_NOMEM; + } jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); parser->pos--; return JSMN_SUCCESS; @@ -85,8 +87,10 @@ static int jsmn_parse_string(jsmn_parser *parser, const char *js, /* Quote: end of string */ if (c == '\"') { token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) + if (token == NULL) { + parser->pos = start; return JSMN_ERROR_NOMEM; + } jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); return JSMN_SUCCESS; } diff --git a/jsmn_test.c b/jsmn_test.c index 81238e7..a356a95 100644 --- a/jsmn_test.c +++ b/jsmn_test.c @@ -244,12 +244,36 @@ int test_partial_array() { return 0; } +int test_array_nomem() { + int i; + int r; + jsmn_parser p; + jsmntok_t toksmall[10], toklarge[10]; + const char *js; + + js = " [ 1, true, [123, \"hello\"]]"; + + for (i = 0; i < 6; i++) { + printf("i = %d\n", i); + jsmn_init(&p); + r = jsmn_parse(&p, js, toksmall, i); + check(r == JSMN_ERROR_NOMEM); + + memcpy(toklarge, toksmall, sizeof(toksmall)); + + r = jsmn_parse(&p, js, toklarge, 10); + check(r == JSMN_SUCCESS); + } + return 0; +} + int main() { test(test_simple, "general test for a simple JSON string"); test(test_primitive, "test primitive JSON data types"); test(test_string, "test string JSON data types"); test(test_partial_string, "test partial JSON string parsing"); test(test_partial_array, "test partial array reading"); + test(test_array_nomem, "test array reading with a smaller number of tokens"); test(test_unquoted_keys, "test unquoted keys (like in JavaScript)"); printf("\nPASSED: %d\nFAILED: %d\n", test_passed, test_failed); return 0;