From e708952c05396980736ff5c1356817761e115841 Mon Sep 17 00:00:00 2001 From: rexy712 Date: Sun, 5 Apr 2020 10:47:12 -0700 Subject: [PATCH] Allow empty string values. Disallow empty key strings --- doc/examples/makefile | 9 ++++++--- doc/examples/parse_file.c | 37 +++++++++++++++++++++++++++++++++++++ src/rjp_parse.c | 4 ++++ src/rjp_string.c | 2 -- 4 files changed, 47 insertions(+), 5 deletions(-) create mode 100644 doc/examples/parse_file.c diff --git a/doc/examples/makefile b/doc/examples/makefile index 48a8e7c..765ab80 100644 --- a/doc/examples/makefile +++ b/doc/examples/makefile @@ -1,11 +1,14 @@ .PHONY: all -all: parse output +all: parse parse_file output -parse: +parse: parse.c gcc -ggdb -I../../include -L../../build parse.c -Wall -Wextra -pedantic -o parse -lrjp -output: +output: output.c gcc -ggdb -I../../include -L../../build output.c -Wall -Wextra -pedantic -o output -lrjp +parse_file: parse_file.c + gcc -ggdb -I../../include -L../../build parse_file.c -Wall -Wextra -pedantic -o parse_file -lrjp clean: rm parse + rm parse_file rm output diff --git a/doc/examples/parse_file.c b/doc/examples/parse_file.c new file mode 100644 index 0000000..b2b3075 --- /dev/null +++ b/doc/examples/parse_file.c @@ -0,0 +1,37 @@ +#include +#include +#include + +int main(int argc, char** argv){ + if(argc != 2){ + fprintf(stderr, "Requires exactly 1 argument\n"); + return 1; + } + + FILE* fp = fopen(argv[1], "rb"); + if(!fp){ + fprintf(stderr, "Unable to open file\n"); + return 1; + } + fseek(fp, 0, SEEK_END); + int buflen = ftell(fp); + fseek(fp, 0, SEEK_SET); + char* buffer = malloc(buflen+1); + fread(buffer, 1, buflen, fp); + buffer[buflen] = 0; + fclose(fp); + + //Read in json argument allowing all RJP extensions (comments, trailing comma) + RJP_value* root = rjp_parse(buffer, RJP_PARSE_ALL_EXT); + + //returns NULL on error + if(!root){ + fprintf(stderr, "Invalid JSON\n"); + return 1; + } + printf("Valid JSON\n"); + + //clean memory + free(buffer); + rjp_free_value(root); +} diff --git a/src/rjp_parse.c b/src/rjp_parse.c index a0057f0..1668ac2 100644 --- a/src/rjp_parse.c +++ b/src/rjp_parse.c @@ -150,6 +150,10 @@ static RJP_value* irjp_add_value_to_array(RJP_lex_category cat, RJP_parse_state* static RJP_value* irjp_add_value_to_object(RJP_parse_state* state, const char* key, RJP_index keylen){ RJP_index newlen; char* newkey = irjp_convert_string(key, keylen, &newlen); + if(!newlen){ //cannot have empty key + rjp_free(newkey); + return NULL; + } return (state->lastadded = rjp_new_member_steal_key(state->curr, newkey, newlen)); } diff --git a/src/rjp_string.c b/src/rjp_string.c index ec2e148..6bdb986 100644 --- a/src/rjp_string.c +++ b/src/rjp_string.c @@ -173,8 +173,6 @@ char* irjp_convert_string(const char* str, RJP_index length, RJP_index* newlen){ return NULL; } } - if(!newlength) - return NULL; newstring = rjp_alloc(newlength + 1); newstring[newlength] = 0; *newlen = newlength;