source: lib/parson.c @ 5726a0d

Last change on this file since 5726a0d was 5726a0d, checked in by Wilmer van der Gaast <wilmer@…>, at 2015-05-04T22:35:13Z

Catch up on parson upstream.
Now at rev 7fd8dc1c4cbc6bc4ce4fef7e1fcbb880a231eae8.

  • Property mode set to 100644
File size: 56.9 KB
Line 
1/*
2 Parson ( http://kgabis.github.com/parson/ )
3 Copyright (c) 2012 - 2014 Krzysztof Gabis
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 THE SOFTWARE.
22*/
23#ifdef _MSC_VER
24#define _CRT_SECURE_NO_WARNINGS
25#endif
26
27#include "parson.h"
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32#include <ctype.h>
33#include <math.h>
34
35#define STARTING_CAPACITY         15
36#define ARRAY_MAX_CAPACITY    122880 /* 15*(2^13) */
37#define OBJECT_MAX_CAPACITY      960 /* 15*(2^6)  */
38#define MAX_NESTING               19
39#define DOUBLE_SERIALIZATION_FORMAT "%f"
40
41#define SIZEOF_TOKEN(a)       (sizeof(a) - 1)
42#define SKIP_CHAR(str)        ((*str)++)
43#define SKIP_WHITESPACES(str) while (isspace(**str)) { SKIP_CHAR(str); }
44#define MAX(a, b)             ((a) > (b) ? (a) : (b))
45
46#define PARSON_MALLOC(a)     malloc(a)
47#define PARSON_FREE(a)       free((void*)(a))
48#define PARSON_REALLOC(a, b) realloc((a), (b))
49
50#define PRINT_AND_SKIP(str, to_append) str += sprintf(str, to_append);
51#define PRINTF_AND_SKIP(str, format, to_append) str += sprintf(str, format, to_append);
52
53#define IS_CONT(b) (((unsigned char)(b) & 0xC0) == 0x80) /* is utf-8 continuation byte */
54
55/* Type definitions */
56typedef union json_value_value {
57    const char  *string;
58    double       number;
59    JSON_Object *object;
60    JSON_Array  *array;
61    int          boolean;
62    int          null;
63} JSON_Value_Value;
64
65struct json_value_t {
66    JSON_Value_Type     type;
67    JSON_Value_Value    value;
68};
69
70struct json_object_t {
71    const char **names;
72    JSON_Value **values;
73    size_t       count;
74    size_t       capacity;
75};
76
77struct json_array_t {
78    JSON_Value **items;
79    size_t       count;
80    size_t       capacity;
81};
82
83/* Various */
84static char * read_file(const char *filename);
85static void   remove_comments(char *string, const char *start_token, const char *end_token);
86static int    try_realloc(void **ptr, size_t new_size);
87static char * parson_strndup(const char *string, size_t n);
88static char * parson_strdup(const char *string);
89static int    is_utf16_hex(const unsigned char *string);
90static int    num_bytes_in_utf8_sequence(unsigned char c);
91static int    verify_utf8_sequence(const unsigned char *string, int *len);
92static int    is_valid_utf8(const char *string, size_t string_len);
93static int    is_decimal(const char *string, size_t length);
94static size_t serialization_strlen(const char *string);
95
96/* JSON Object */
97static JSON_Object * json_object_init(void);
98static JSON_Status   json_object_add(JSON_Object *object, const char *name, JSON_Value *value);
99static JSON_Status   json_object_resize(JSON_Object *object, size_t capacity);
100static JSON_Value  * json_object_nget_value(const JSON_Object *object, const char *name, size_t n);
101static void          json_object_free(JSON_Object *object);
102
103/* JSON Array */
104static JSON_Array * json_array_init(void);
105static JSON_Status  json_array_add(JSON_Array *array, JSON_Value *value);
106static JSON_Status  json_array_resize(JSON_Array *array, size_t capacity);
107static void         json_array_free(JSON_Array *array);
108
109/* JSON Value */
110static JSON_Value * json_value_init_string_no_copy(const char *string);
111
112/* Parser */
113static void         skip_quotes(const char **string);
114static int          parse_utf_16(const char **unprocessed, char **processed);
115static char*        process_string(const char *input, size_t len);
116static const char * get_quoted_string(const char **string);
117static JSON_Value * parse_object_value(const char **string, size_t nesting);
118static JSON_Value * parse_array_value(const char **string, size_t nesting);
119static JSON_Value * parse_string_value(const char **string);
120static JSON_Value * parse_boolean_value(const char **string);
121static JSON_Value * parse_number_value(const char **string);
122static JSON_Value * parse_null_value(const char **string);
123static JSON_Value * parse_value(const char **string, size_t nesting);
124
125/* Serialization */
126static size_t json_serialization_size_r(const JSON_Value *value, char *buf);
127static char * json_serialize_to_buffer_r(const JSON_Value *value, char *buf);
128static char * json_serialize_string(const char *string, char *buf);
129
130/* Various */
131static int try_realloc(void **ptr, size_t new_size) {
132    void *reallocated_ptr = NULL;
133    if (new_size == 0) {
134        return JSONFailure;
135    }
136    reallocated_ptr = PARSON_REALLOC(*ptr, new_size);
137    if (reallocated_ptr == NULL) {
138        return JSONFailure;
139    }
140    *ptr = reallocated_ptr;
141    return JSONSuccess;
142}
143
144static char * parson_strndup(const char *string, size_t n) {
145    char *output_string = (char*)PARSON_MALLOC(n + 1);
146    if (!output_string)
147        return NULL;
148    output_string[n] = '\0';
149    strncpy(output_string, string, n);
150    return output_string;
151}
152
153static char * parson_strdup(const char *string) {
154    return parson_strndup(string, strlen(string));
155}
156
157static int is_utf16_hex(const unsigned char *s) {
158    return isxdigit(s[0]) && isxdigit(s[1]) && isxdigit(s[2]) && isxdigit(s[3]);
159}
160
161static int num_bytes_in_utf8_sequence(unsigned char c) {
162    if (c == 0xC0 || c == 0xC1 || c > 0xF4 || IS_CONT(c)) {
163        return 0;
164    } else if ((c & 0x80) == 0) {    /* 0xxxxxxx */
165        return 1;
166    } else if ((c & 0xE0) == 0xC0) { /* 110xxxxx */
167        return 2;
168    } else if ((c & 0xF0) == 0xE0) { /* 1110xxxx */
169        return 3;
170    } else if ((c & 0xF8) == 0xF0) { /* 11110xxx */
171        return 4;
172    }
173    return 0; /* won't happen */
174}
175
176static int verify_utf8_sequence(const unsigned char *string, int *len) {
177    unsigned int cp = 0;
178    *len = num_bytes_in_utf8_sequence(string[0]);
179   
180    if (*len == 1) {
181        cp = string[0];
182    } else if (*len == 2 && IS_CONT(string[1])) {
183        cp = string[0] & 0x1F;
184        cp = (cp << 6) | (string[1] & 0x3F);
185    } else if (*len == 3 && IS_CONT(string[1]) && IS_CONT(string[2])) {
186        cp = ((unsigned char)string[0]) & 0xF;
187        cp = (cp << 6) | (string[1] & 0x3F);
188        cp = (cp << 6) | (string[2] & 0x3F);
189    } else if (*len == 4 && IS_CONT(string[1]) && IS_CONT(string[2]) && IS_CONT(string[3])) {
190        cp = string[0] & 0x7;
191        cp = (cp << 6) | (string[1] & 0x3F);
192        cp = (cp << 6) | (string[2] & 0x3F);
193        cp = (cp << 6) | (string[3] & 0x3F);
194    } else {
195        return 0;
196    }
197   
198    /* overlong encodings */
199    if ((cp < 0x80    && *len > 1) ||
200        (cp < 0x800   && *len > 2) ||
201        (cp < 0x10000 && *len > 3)) {
202        return 0;
203    }
204   
205    /* invalid unicode */
206    if (cp > 0x10FFFF) {
207        return 0;
208    }
209   
210    /* surrogate halves */
211    if (cp >= 0xD800 && cp <= 0xDFFF) {
212        return 0;
213    }
214   
215    return 1;
216}
217
218static int is_valid_utf8(const char *string, size_t string_len) {
219    int len = 0;
220    const char *string_end =  string + string_len;
221    while (string < string_end) {
222        if (!verify_utf8_sequence((const unsigned char*)string, &len)) {
223            return 0;
224        }
225        string += len;
226    }
227    return 1;
228}
229
230static int is_decimal(const char *string, size_t length) {
231    if (length > 1 && string[0] == '0' && string[1] != '.')
232        return 0;
233    if (length > 2 && !strncmp(string, "-0", 2) && string[2] != '.')
234        return 0;
235    while (length--)
236        if (strchr("xX", string[length]))
237            return 0;
238    return 1;
239}
240
241static size_t serialization_strlen(const char *string) {
242    size_t result = 0;
243    size_t i = 0, len = strlen(string);
244    for (i = 0; i < len; i++) {
245        if (strchr("\"\\\b\f\n\r\t", string[i])) /* must be escaped */
246            result += 2;
247        else
248            result += 1;
249    }
250    return result;
251}
252
253static char * read_file(const char * filename) {
254    FILE *fp = fopen(filename, "r");
255    size_t file_size;
256    long pos;
257    char *file_contents;
258    if (!fp)
259        return NULL;
260    fseek(fp, 0L, SEEK_END);
261    pos = ftell(fp);
262    if (pos < 0) {
263        fclose(fp);
264        return NULL;
265    }
266    file_size = pos;
267    rewind(fp);
268    file_contents = (char*)PARSON_MALLOC(sizeof(char) * (file_size + 1));
269    if (!file_contents) {
270        fclose(fp);
271        return NULL;
272    }
273    if (fread(file_contents, file_size, 1, fp) < 1) {
274        if (ferror(fp)) {
275            fclose(fp);
276            PARSON_FREE(file_contents);
277            return NULL;
278        }
279    }
280    fclose(fp);
281    file_contents[file_size] = '\0';
282    return file_contents;
283}
284
285static void remove_comments(char *string, const char *start_token, const char *end_token) {
286    int in_string = 0, escaped = 0;
287    size_t i;
288    char *ptr = NULL, current_char;
289    size_t start_token_len = strlen(start_token);
290    size_t end_token_len = strlen(end_token);
291    if (start_token_len == 0 || end_token_len == 0)
292        return;
293    while ((current_char = *string) != '\0') {
294        if (current_char == '\\' && !escaped) {
295            escaped = 1;
296            string++;
297            continue;
298        } else if (current_char == '\"' && !escaped) {
299            in_string = !in_string;
300        } else if (!in_string && strncmp(string, start_token, start_token_len) == 0) {
301                        for(i = 0; i < start_token_len; i++)
302                string[i] = ' ';
303                string = string + start_token_len;
304            ptr = strstr(string, end_token);
305            if (!ptr)
306                return;
307            for (i = 0; i < (ptr - string) + end_token_len; i++)
308                string[i] = ' ';
309                string = ptr + end_token_len - 1;
310        }
311        escaped = 0;
312        string++;
313    }
314}
315
316/* JSON Object */
317static JSON_Object * json_object_init(void) {
318    JSON_Object *new_obj = (JSON_Object*)PARSON_MALLOC(sizeof(JSON_Object));
319    if (!new_obj)
320        return NULL;
321    new_obj->names = (const char**)NULL;
322    new_obj->values = (JSON_Value**)NULL;
323    new_obj->capacity = 0;
324    new_obj->count = 0;
325    return new_obj;
326}
327
328static JSON_Status json_object_add(JSON_Object *object, const char *name, JSON_Value *value) {
329    size_t index = 0;
330    if (object == NULL || name == NULL || value == NULL) {
331        return JSONFailure;
332    }
333    if (object->count >= object->capacity) {
334        size_t new_capacity = MAX(object->capacity * 2, STARTING_CAPACITY);
335        if (new_capacity > OBJECT_MAX_CAPACITY)
336            return JSONFailure;
337        if (json_object_resize(object, new_capacity) == JSONFailure)
338            return JSONFailure;
339    }
340    if (json_object_get_value(object, name) != NULL)
341        return JSONFailure;
342    index = object->count;
343    object->names[index] = parson_strdup(name);
344    if (object->names[index] == NULL)
345        return JSONFailure;
346    object->values[index] = value;
347    object->count++;
348    return JSONSuccess;
349}
350
351static JSON_Status json_object_resize(JSON_Object *object, size_t capacity) {
352    if (try_realloc((void**)&object->names, capacity * sizeof(char*)) == JSONFailure)
353        return JSONFailure;
354    if (try_realloc((void**)&object->values, capacity * sizeof(JSON_Value*)) == JSONFailure)
355        return JSONFailure;
356    object->capacity = capacity;
357    return JSONSuccess;
358}
359
360static JSON_Value * json_object_nget_value(const JSON_Object *object, const char *name, size_t n) {
361    size_t i, name_length;
362    for (i = 0; i < json_object_get_count(object); i++) {
363        name_length = strlen(object->names[i]);
364        if (name_length != n)
365            continue;
366        if (strncmp(object->names[i], name, n) == 0)
367            return object->values[i];
368    }
369    return NULL;
370}
371
372static void json_object_free(JSON_Object *object) {
373    while(object->count--) {
374        PARSON_FREE(object->names[object->count]);
375        json_value_free(object->values[object->count]);
376    }
377    PARSON_FREE(object->names);
378    PARSON_FREE(object->values);
379    PARSON_FREE(object);
380}
381
382/* JSON Array */
383static JSON_Array * json_array_init(void) {
384    JSON_Array *new_array = (JSON_Array*)PARSON_MALLOC(sizeof(JSON_Array));
385    if (!new_array)
386        return NULL;
387    new_array->items = (JSON_Value**)NULL;
388    new_array->capacity = 0;
389    new_array->count = 0;
390    return new_array;
391}
392
393static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value) {
394    if (array->count >= array->capacity) {
395        size_t new_capacity = MAX(array->capacity * 2, STARTING_CAPACITY);
396        if (new_capacity > ARRAY_MAX_CAPACITY)
397            return JSONFailure;
398        if (json_array_resize(array, new_capacity) == JSONFailure)
399            return JSONFailure;
400    }
401    array->items[array->count] = value;
402    array->count++;
403    return JSONSuccess;
404}
405
406static JSON_Status json_array_resize(JSON_Array *array, size_t capacity) {
407    if (try_realloc((void**)&array->items, capacity * sizeof(JSON_Value*)) == JSONFailure)
408        return JSONFailure;
409    array->capacity = capacity;
410    return JSONSuccess;
411}
412
413static void json_array_free(JSON_Array *array) {
414    while (array->count--)
415        json_value_free(array->items[array->count]);
416    PARSON_FREE(array->items);
417    PARSON_FREE(array);
418}
419
420/* JSON Value */
421static JSON_Value * json_value_init_string_no_copy(const char *string) {
422    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
423    if (!new_value)
424        return NULL;
425    new_value->type = JSONString;
426    new_value->value.string = string;
427    return new_value;
428}
429
430/* Parser */
431static void skip_quotes(const char **string) {
432    SKIP_CHAR(string);
433    while (**string != '\"') {
434        if (**string == '\0')
435            return;
436        if (**string == '\\') {
437            SKIP_CHAR(string);
438            if (**string == '\0')
439                return;
440        }
441        SKIP_CHAR(string);
442    }
443    SKIP_CHAR(string);
444}
445
446static int parse_utf_16(const char **unprocessed, char **processed) {
447    unsigned int cp, lead, trail;
448    char *processed_ptr = *processed;
449    const char *unprocessed_ptr = *unprocessed;
450    unprocessed_ptr++; /* skips u */
451    if (!is_utf16_hex((const unsigned char*)unprocessed_ptr) || sscanf(unprocessed_ptr, "%4x", &cp) == EOF)
452            return JSONFailure;
453    if (cp < 0x80) {
454        *processed_ptr = cp; /* 0xxxxxxx */
455    } else if (cp < 0x800) {
456        *processed_ptr++ = ((cp >> 6) & 0x1F) | 0xC0; /* 110xxxxx */
457        *processed_ptr   = ((cp     ) & 0x3F) | 0x80; /* 10xxxxxx */
458    } else if (cp < 0xD800 || cp > 0xDFFF) {
459        *processed_ptr++ = ((cp >> 12) & 0x0F) | 0xE0; /* 1110xxxx */
460        *processed_ptr++ = ((cp >> 6)  & 0x3F) | 0x80; /* 10xxxxxx */
461        *processed_ptr   = ((cp     )  & 0x3F) | 0x80; /* 10xxxxxx */
462    } else if (cp >= 0xD800 && cp <= 0xDBFF) { /* lead surrogate (0xD800..0xDBFF) */
463        lead = cp;
464        unprocessed_ptr += 4; /* should always be within the buffer, otherwise previous sscanf would fail */
465        if (*unprocessed_ptr++ != '\\' || *unprocessed_ptr++ != 'u' || /* starts with \u? */
466            !is_utf16_hex((const unsigned char*)unprocessed_ptr)          ||
467            sscanf(unprocessed_ptr, "%4x", &trail) == EOF           ||
468            trail < 0xDC00 || trail > 0xDFFF) { /* valid trail surrogate? (0xDC00..0xDFFF) */
469                return JSONFailure;
470        }
471        cp = ((((lead-0xD800)&0x3FF)<<10)|((trail-0xDC00)&0x3FF))+0x010000;
472        *processed_ptr++ = (((cp >> 18) & 0x07) | 0xF0); /* 11110xxx */
473        *processed_ptr++ = (((cp >> 12) & 0x3F) | 0x80); /* 10xxxxxx */
474        *processed_ptr++ = (((cp >> 6)  & 0x3F) | 0x80); /* 10xxxxxx */
475        *processed_ptr   = (((cp     )  & 0x3F) | 0x80); /* 10xxxxxx */
476    } else { /* trail surrogate before lead surrogate */
477        return JSONFailure;
478    }
479    unprocessed_ptr += 3;
480    *processed = processed_ptr;
481    *unprocessed = unprocessed_ptr;
482    return JSONSuccess;
483}
484
485
486/* Copies and processes passed string up to supplied length.
487Example: "\u006Corem ipsum" -> lorem ipsum */
488static char* process_string(const char *input, size_t len) {
489    const char *input_ptr = input;
490    char *output = (char*)PARSON_MALLOC((len + 1) * sizeof(char));
491    char *output_ptr = output;
492    while ((*input_ptr != '\0') && (size_t)(input_ptr - input) < len) {
493        if (*input_ptr == '\\') {
494            input_ptr++;
495            switch (*input_ptr) {
496                case '\"': *output_ptr = '\"'; break;
497                case '\\': *output_ptr = '\\'; break;
498                case '/':  *output_ptr = '/';  break;
499                case 'b':  *output_ptr = '\b'; break;
500                case 'f':  *output_ptr = '\f'; break;
501                case 'n':  *output_ptr = '\n'; break;
502                case 'r':  *output_ptr = '\r'; break;
503                case 't':  *output_ptr = '\t'; break;
504                case 'u':
505                    if (parse_utf_16(&input_ptr, &output_ptr) == JSONFailure)
506                        goto error;
507                    break;
508                default:
509                    goto error;
510            }
511        } else if ((unsigned char)*input_ptr < 0x20) {
512            goto error; /* 0x00-0x19 are invalid characters for json string (http://www.ietf.org/rfc/rfc4627.txt) */
513        } else {
514            *output_ptr = *input_ptr;
515        }
516        output_ptr++;
517        input_ptr++;
518    }
519    *output_ptr = '\0';
520    if (try_realloc((void**)&output, (size_t)(output_ptr-output) + 1) == JSONFailure) /* resize to new length */
521        goto error;
522    return output;
523error:
524    free(output);
525    return NULL;
526}
527
528/* Return processed contents of a string between quotes and
529   skips passed argument to a matching quote. */
530static const char * get_quoted_string(const char **string) {
531    const char *string_start = *string;
532    size_t string_len = 0;
533    skip_quotes(string);
534    if (**string == '\0')
535        return NULL;
536    string_len = *string - string_start - 2; /* length without quotes */
537    return process_string(string_start + 1, string_len);
538}
539
540static JSON_Value * parse_value(const char **string, size_t nesting) {
541    if (nesting > MAX_NESTING)
542        return NULL;
543    SKIP_WHITESPACES(string);
544    switch (**string) {
545        case '{':
546            return parse_object_value(string, nesting + 1);
547        case '[':
548            return parse_array_value(string, nesting + 1);
549        case '\"':
550            return parse_string_value(string);
551        case 'f': case 't':
552            return parse_boolean_value(string);
553        case '-':
554        case '0': case '1': case '2': case '3': case '4':
555        case '5': case '6': case '7': case '8': case '9':
556            return parse_number_value(string);
557        case 'n':
558            return parse_null_value(string);
559        default:
560            return NULL;
561    }
562}
563
564static JSON_Value * parse_object_value(const char **string, size_t nesting) {
565    JSON_Value *output_value = json_value_init_object(), *new_value = NULL;
566    JSON_Object *output_object = json_value_get_object(output_value);
567    const char *new_key = NULL;
568    if (output_value == NULL)
569        return NULL;
570    SKIP_CHAR(string);
571    SKIP_WHITESPACES(string);
572    if (**string == '}') { /* empty object */
573        SKIP_CHAR(string);
574        return output_value;
575    }
576    while (**string != '\0') {
577        new_key = get_quoted_string(string);
578        SKIP_WHITESPACES(string);
579        if (new_key == NULL || **string != ':') {
580            json_value_free(output_value);
581            return NULL;
582        }
583        SKIP_CHAR(string);
584        new_value = parse_value(string, nesting);
585        if (new_value == NULL) {
586            PARSON_FREE(new_key);
587            json_value_free(output_value);
588            return NULL;
589        }
590        if(json_object_add(output_object, new_key, new_value) == JSONFailure) {
591            PARSON_FREE(new_key);
592            PARSON_FREE(new_value);
593            json_value_free(output_value);
594            return NULL;
595        }
596        PARSON_FREE(new_key);
597        SKIP_WHITESPACES(string);
598        if (**string != ',')
599            break;
600        SKIP_CHAR(string);
601        SKIP_WHITESPACES(string);
602    }
603    SKIP_WHITESPACES(string);
604    if (**string != '}' || /* Trim object after parsing is over */
605        json_object_resize(output_object, json_object_get_count(output_object)) == JSONFailure) {
606            json_value_free(output_value);
607            return NULL;
608    }
609    SKIP_CHAR(string);
610    return output_value;
611}
612
613static JSON_Value * parse_array_value(const char **string, size_t nesting) {
614    JSON_Value *output_value = json_value_init_array(), *new_array_value = NULL;
615    JSON_Array *output_array = json_value_get_array(output_value);
616    if (!output_value)
617        return NULL;
618    SKIP_CHAR(string);
619    SKIP_WHITESPACES(string);
620    if (**string == ']') { /* empty array */
621        SKIP_CHAR(string);
622        return output_value;
623    }
624    while (**string != '\0') {
625        new_array_value = parse_value(string, nesting);
626        if (!new_array_value) {
627            json_value_free(output_value);
628            return NULL;
629        }
630        if(json_array_add(output_array, new_array_value) == JSONFailure) {
631            PARSON_FREE(new_array_value);
632            json_value_free(output_value);
633            return NULL;
634        }
635        SKIP_WHITESPACES(string);
636        if (**string != ',')
637            break;
638        SKIP_CHAR(string);
639        SKIP_WHITESPACES(string);
640    }
641    SKIP_WHITESPACES(string);
642    if (**string != ']' || /* Trim array after parsing is over */
643        json_array_resize(output_array, json_array_get_count(output_array)) == JSONFailure) {
644            json_value_free(output_value);
645            return NULL;
646    }
647    SKIP_CHAR(string);
648    return output_value;
649}
650
651static JSON_Value * parse_string_value(const char **string) {
652    const char *new_string = get_quoted_string(string);
653    if (!new_string)
654        return NULL;
655    return json_value_init_string_no_copy(new_string);
656}
657
658static JSON_Value * parse_boolean_value(const char **string) {
659    size_t true_token_size = SIZEOF_TOKEN("true");
660    size_t false_token_size = SIZEOF_TOKEN("false");
661    if (strncmp("true", *string, true_token_size) == 0) {
662        *string += true_token_size;
663        return json_value_init_boolean(1);
664    } else if (strncmp("false", *string, false_token_size) == 0) {
665        *string += false_token_size;
666        return json_value_init_boolean(0);
667    }
668    return NULL;
669}
670
671static JSON_Value * parse_number_value(const char **string) {
672    char *end;
673    double number = strtod(*string, &end);
674    JSON_Value *output_value;
675    if (is_decimal(*string, end - *string)) {
676        *string = end;
677        output_value = json_value_init_number(number);
678    } else {
679        output_value = NULL;
680    }
681    return output_value;
682}
683
684static JSON_Value * parse_null_value(const char **string) {
685    size_t token_size = SIZEOF_TOKEN("null");
686    if (strncmp("null", *string, token_size) == 0) {
687        *string += token_size;
688        return json_value_init_null();
689    }
690    return NULL;
691}
692
693/* Serialization */
694static size_t json_serialization_size_r(const JSON_Value *value, char *buf) {
695    size_t result_size = 0;
696    const char *key = NULL;
697    JSON_Value *temp_value = NULL;
698    JSON_Array *array = NULL;
699    JSON_Object *object = NULL;
700    size_t i = 0, count = 0;
701    double num = 0.0;
702    switch (json_value_get_type(value)) {
703        case JSONArray:
704            array = json_value_get_array(value);
705            count = json_array_get_count(array);
706            result_size += 2; /* [ and ] brackets */
707            if (count > 0)
708                result_size += count - 1; /* , between items */
709            for (i = 0; i < count; i++) {
710                temp_value = json_array_get_value(array, i);
711                result_size += json_serialization_size_r(temp_value, buf);
712            }
713            return result_size;
714        case JSONObject:
715            object = json_value_get_object(value);
716            count  = json_object_get_count(object);
717            result_size += 2; /* { and } brackets */
718            if (count > 0)
719                result_size += (count * 2) - 1; /* : between keys and values and , between items */
720            for (i = 0; i < count; i++) {
721                key = json_object_get_name(object, i);
722                result_size += serialization_strlen(key) + 2; /* string and quotes */
723                result_size += json_serialization_size_r(json_object_get_value(object, key), buf);
724            }
725            return result_size;
726        case JSONString:
727            return serialization_strlen(json_value_get_string(value)) + 2; /* string and quotes */
728        case JSONBoolean:
729            if (json_value_get_boolean(value))
730                return 4; /* strlen("true"); */
731            else
732                return 5; /* strlen("false"); */
733        case JSONNumber:
734            num = json_value_get_number(value);
735            if (num == ((double)(int)num) ) /*  check if num is integer */
736                return (size_t)sprintf(buf, "%d", (int)num);
737            return (size_t)sprintf(buf, DOUBLE_SERIALIZATION_FORMAT, num);
738        case JSONNull:
739            return 4; /* strlen("null"); */
740        case JSONError:
741            return 0;
742        default:
743            return 0;
744    }
745}
746
747char* json_serialize_to_buffer_r(const JSON_Value *value, char *buf)
748{
749    const char *key = NULL, *string = NULL;
750    JSON_Value *temp_value = NULL;
751    JSON_Array *array = NULL;
752    JSON_Object *object = NULL;
753    size_t i = 0, count = 0;
754    double num = 0.0;
755    switch (json_value_get_type(value)) {
756        case JSONArray:
757            array = json_value_get_array(value);
758            count = json_array_get_count(array);
759            PRINT_AND_SKIP(buf, "[");
760            for (i = 0; i < count; i++) {
761                temp_value = json_array_get_value(array, i);
762                buf = json_serialize_to_buffer_r(temp_value, buf);
763                if (buf == NULL)
764                    return NULL;
765                if (i < (count - 1))
766                    PRINT_AND_SKIP(buf, ",");
767            }
768            PRINT_AND_SKIP(buf, "]");
769            return buf;
770        case JSONObject:
771            object = json_value_get_object(value);
772            count  = json_object_get_count(object);
773            PRINT_AND_SKIP(buf, "{");
774            for (i = 0; i < count; i++) {
775                key = json_object_get_name(object, i);
776                buf = json_serialize_string(key, buf);
777                if (buf == NULL)
778                    return NULL;
779                PRINT_AND_SKIP(buf, ":");
780                temp_value = json_object_get_value(object, key);
781                buf = json_serialize_to_buffer_r(temp_value, buf);
782                if (buf == NULL)
783                    return NULL;
784                if (i < (count - 1))
785                    PRINT_AND_SKIP(buf, ",");
786            }
787            PRINT_AND_SKIP(buf, "}");
788            return buf;
789        case JSONString:
790            string = json_value_get_string(value);
791            buf = json_serialize_string(string, buf);
792            return buf;
793        case JSONBoolean:
794            if (json_value_get_boolean(value)) {
795                PRINT_AND_SKIP(buf, "true");
796            } else {
797                PRINT_AND_SKIP(buf, "false");
798            }
799            return buf;
800        case JSONNumber:
801            num = json_value_get_number(value);
802            if (num == ((double)(int)num)) { /*  check if num is integer */
803                PRINTF_AND_SKIP(buf, "%d", (int)num);
804            } else {
805                PRINTF_AND_SKIP(buf, DOUBLE_SERIALIZATION_FORMAT, num);
806            }
807            return buf;
808        case JSONNull:
809            PRINT_AND_SKIP(buf, "null");
810            return buf;
811        case JSONError:
812            return NULL;
813        default:
814            return NULL;
815    }
816}
817
818static char * json_serialize_string(const char *string, char *buf) {
819    size_t i = 0, len = strlen(string);
820    char c = '\0';
821    PRINT_AND_SKIP(buf, "\"")
822    for (i = 0; i < len; i++) {
823        c = string[i];
824        switch (c) {
825            case '\"': PRINT_AND_SKIP(buf, "\\\"");   break;
826            case '\\': PRINT_AND_SKIP(buf, "\\\\");   break;
827            case '\b': PRINT_AND_SKIP(buf, "\\b");    break;
828            case '\f': PRINT_AND_SKIP(buf, "\\f");    break;
829            case '\n': PRINT_AND_SKIP(buf, "\\n");    break;
830            case '\r': PRINT_AND_SKIP(buf, "\\r");    break;
831            case '\t': PRINT_AND_SKIP(buf, "\\t");    break;
832            default:   PRINTF_AND_SKIP(buf, "%c", c); break;
833        }
834    }
835    PRINT_AND_SKIP(buf, "\"");
836    return buf;
837}
838
839/* Parser API */
840JSON_Value * json_parse_file(const char *filename) {
841    char *file_contents = read_file(filename);
842    JSON_Value *output_value = NULL;
843    if (file_contents == NULL)
844        return NULL;
845    output_value = json_parse_string(file_contents);
846    PARSON_FREE(file_contents);
847    return output_value;
848}
849
850JSON_Value * json_parse_file_with_comments(const char *filename) {
851    char *file_contents = read_file(filename);
852    JSON_Value *output_value = NULL;
853    if (file_contents == NULL)
854        return NULL;
855    output_value = json_parse_string_with_comments(file_contents);
856    PARSON_FREE(file_contents);
857    return output_value;
858}
859
860JSON_Value * json_parse_first(const char *string, const char **end) {
861    const char *pos;
862    JSON_Value *ret;
863
864    if (string == NULL)
865        return NULL;
866    SKIP_WHITESPACES(&string);
867    if (*string != '{' && *string != '[')
868        return NULL;
869
870    pos = string;
871    ret = parse_value(&pos, 0);
872    if (end)
873        *end = pos;
874
875    return ret;
876}
877
878JSON_Value * json_parse_string(const char *string) {
879    return json_parse_first(string, NULL);
880}
881
882JSON_Value * json_parse_string_with_comments(const char *string) {
883    JSON_Value *result = NULL;
884    char *string_mutable_copy = NULL, *string_mutable_copy_ptr = NULL;
885    string_mutable_copy = parson_strdup(string);
886    if (string_mutable_copy == NULL)
887        return NULL;
888    remove_comments(string_mutable_copy, "/*", "*/");
889    remove_comments(string_mutable_copy, "//", "\n");
890    string_mutable_copy_ptr = string_mutable_copy;
891    SKIP_WHITESPACES(&string_mutable_copy_ptr);
892    if (*string_mutable_copy_ptr != '{' && *string_mutable_copy_ptr != '[') {
893        PARSON_FREE(string_mutable_copy);
894        return NULL;
895    }
896    result = parse_value((const char**)&string_mutable_copy_ptr, 0);
897    PARSON_FREE(string_mutable_copy);
898    return result;
899}
900
901
902/* JSON Object API */
903
904JSON_Value * json_object_get_value(const JSON_Object *object, const char *name) {
905    if (object == NULL || name == NULL)
906        return NULL;
907    return json_object_nget_value(object, name, strlen(name));
908}
909
910const char * json_object_get_string(const JSON_Object *object, const char *name) {
911    return json_value_get_string(json_object_get_value(object, name));
912}
913
914double json_object_get_number(const JSON_Object *object, const char *name) {
915    return json_value_get_number(json_object_get_value(object, name));
916}
917
918JSON_Object * json_object_get_object(const JSON_Object *object, const char *name) {
919    return json_value_get_object(json_object_get_value(object, name));
920}
921
922JSON_Array * json_object_get_array(const JSON_Object *object, const char *name) {
923    return json_value_get_array(json_object_get_value(object, name));
924}
925
926int json_object_get_boolean(const JSON_Object *object, const char *name) {
927    return json_value_get_boolean(json_object_get_value(object, name));
928}
929
930JSON_Value * json_object_dotget_value(const JSON_Object *object, const char *name) {
931    const char *dot_position = strchr(name, '.');
932    if (!dot_position)
933        return json_object_get_value(object, name);
934    object = json_value_get_object(json_object_nget_value(object, name, dot_position - name));
935    return json_object_dotget_value(object, dot_position + 1);
936}
937
938const char * json_object_dotget_string(const JSON_Object *object, const char *name) {
939    return json_value_get_string(json_object_dotget_value(object, name));
940}
941
942double json_object_dotget_number(const JSON_Object *object, const char *name) {
943    return json_value_get_number(json_object_dotget_value(object, name));
944}
945
946JSON_Object * json_object_dotget_object(const JSON_Object *object, const char *name) {
947    return json_value_get_object(json_object_dotget_value(object, name));
948}
949
950JSON_Array * json_object_dotget_array(const JSON_Object *object, const char *name) {
951    return json_value_get_array(json_object_dotget_value(object, name));
952}
953
954int json_object_dotget_boolean(const JSON_Object *object, const char *name) {
955    return json_value_get_boolean(json_object_dotget_value(object, name));
956}
957
958size_t json_object_get_count(const JSON_Object *object) {
959    return object ? object->count : 0;
960}
961
962const char * json_object_get_name(const JSON_Object *object, size_t index) {
963    if (index >= json_object_get_count(object))
964        return NULL;
965    return object->names[index];
966}
967
968int json_object_get_tuple(const JSON_Object *object, size_t index,
969                          const char **key, const JSON_Value **value) {
970    if (index >= json_object_get_count(object))
971        return 0;
972    *key = object->names[index];
973    *value = object->values[index];
974    return 1;
975}
976
977/* JSON Array API */
978JSON_Value * json_array_get_value(const JSON_Array *array, size_t index) {
979    if (index >= json_array_get_count(array))
980        return NULL;
981    return array->items[index];
982}
983
984const char * json_array_get_string(const JSON_Array *array, size_t index) {
985    return json_value_get_string(json_array_get_value(array, index));
986}
987
988double json_array_get_number(const JSON_Array *array, size_t index) {
989    return json_value_get_number(json_array_get_value(array, index));
990}
991
992JSON_Object * json_array_get_object(const JSON_Array *array, size_t index) {
993    return json_value_get_object(json_array_get_value(array, index));
994}
995
996JSON_Array * json_array_get_array(const JSON_Array *array, size_t index) {
997    return json_value_get_array(json_array_get_value(array, index));
998}
999
1000int json_array_get_boolean(const JSON_Array *array, size_t index) {
1001    return json_value_get_boolean(json_array_get_value(array, index));
1002}
1003
1004size_t json_array_get_count(const JSON_Array *array) {
1005    return array ? array->count : 0;
1006}
1007
1008/* JSON Value API */
1009JSON_Value_Type json_value_get_type(const JSON_Value *value) {
1010    return value ? value->type : JSONError;
1011}
1012
1013JSON_Object * json_value_get_object(const JSON_Value *value) {
1014    return json_value_get_type(value) == JSONObject ? value->value.object : NULL;
1015}
1016
1017JSON_Array * json_value_get_array(const JSON_Value *value) {
1018    return json_value_get_type(value) == JSONArray ? value->value.array : NULL;
1019}
1020
1021const char * json_value_get_string(const JSON_Value *value) {
1022    return json_value_get_type(value) == JSONString ? value->value.string : NULL;
1023}
1024
1025double json_value_get_number(const JSON_Value *value) {
1026    return json_value_get_type(value) == JSONNumber ? value->value.number : 0;
1027}
1028
1029int json_value_get_boolean(const JSON_Value *value) {
1030    return json_value_get_type(value) == JSONBoolean ? value->value.boolean : -1;
1031}
1032
1033void json_value_free(JSON_Value *value) {
1034    switch (json_value_get_type(value)) {
1035        case JSONObject:
1036            json_object_free(value->value.object);
1037            break;
1038        case JSONString:
1039            if (value->value.string) { PARSON_FREE(value->value.string); }
1040            break;
1041        case JSONArray:
1042            json_array_free(value->value.array);
1043            break;
1044        default:
1045            break;
1046    }
1047    PARSON_FREE(value);
1048}
1049
1050JSON_Value * json_value_init_object(void) {
1051    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
1052    if (!new_value)
1053        return NULL;
1054    new_value->type = JSONObject;
1055    new_value->value.object = json_object_init();
1056    if (!new_value->value.object) {
1057        PARSON_FREE(new_value);
1058        return NULL;
1059    }
1060    return new_value;
1061}
1062
1063JSON_Value * json_value_init_array(void) {
1064    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
1065    if (!new_value)
1066        return NULL;
1067    new_value->type = JSONArray;
1068    new_value->value.array = json_array_init();
1069    if (!new_value->value.array) {
1070        PARSON_FREE(new_value);
1071        return NULL;
1072    }
1073    return new_value;
1074}
1075
1076JSON_Value * json_value_init_string(const char *string) {
1077    char *copy = NULL;
1078    JSON_Value *value;
1079    size_t string_len = 0;
1080    if (string == NULL)
1081        return NULL;
1082    string_len = strlen(string);
1083    if (!is_valid_utf8(string, string_len))
1084        return NULL;
1085    copy = parson_strndup(string, string_len);
1086    if (copy == NULL)
1087        return NULL;
1088    value = json_value_init_string_no_copy(copy);
1089    if (value == NULL)
1090        PARSON_FREE(copy);
1091    return value;
1092}
1093
1094JSON_Value * json_value_init_number(double number) {
1095    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
1096    if (!new_value)
1097        return NULL;
1098    new_value->type = JSONNumber;
1099    new_value->value.number = number;
1100    return new_value;
1101}
1102
1103JSON_Value * json_value_init_boolean(int boolean) {
1104    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
1105    if (!new_value)
1106        return NULL;
1107    new_value->type = JSONBoolean;
1108    new_value->value.boolean = boolean ? 1 : 0;
1109    return new_value;
1110}
1111
1112JSON_Value * json_value_init_null(void) {
1113    JSON_Value *new_value = (JSON_Value*)PARSON_MALLOC(sizeof(JSON_Value));
1114    if (!new_value)
1115        return NULL;
1116    new_value->type = JSONNull;
1117    return new_value;
1118}
1119
1120JSON_Value * json_value_deep_copy(const JSON_Value *value) {
1121    size_t i = 0;
1122    JSON_Value *return_value = NULL, *temp_value_copy = NULL, *temp_value = NULL;
1123    const char *temp_string = NULL, *temp_string_copy = NULL, *temp_key = NULL;
1124    JSON_Array *temp_array = NULL, *temp_array_copy = NULL;
1125    JSON_Object *temp_object = NULL, *temp_object_copy = NULL;
1126   
1127    switch (json_value_get_type(value)) {
1128        case JSONArray:
1129            temp_array = json_value_get_array(value);
1130            return_value = json_value_init_array();
1131            if (return_value == NULL)
1132                return NULL;
1133            temp_array_copy = json_value_get_array(return_value);
1134            for (i = 0; i < json_array_get_count(temp_array); i++) {
1135                temp_value = json_array_get_value(temp_array, i);
1136                temp_value_copy = json_value_deep_copy(temp_value);
1137                if (temp_value_copy == NULL) {
1138                    json_value_free(return_value);
1139                    return NULL;
1140                }
1141                if (json_array_add(temp_array_copy, temp_value_copy) == JSONFailure) {
1142                    json_value_free(return_value);
1143                    json_value_free(temp_value_copy);
1144                    return NULL;
1145                }
1146            }
1147            return return_value;
1148        case JSONObject:
1149            temp_object = json_value_get_object(value);
1150            return_value = json_value_init_object();
1151            if (return_value == NULL)
1152                return NULL;
1153            temp_object_copy = json_value_get_object(return_value);
1154            for (i = 0; i < json_object_get_count(temp_object); i++) {
1155                temp_key = json_object_get_name(temp_object, i);
1156                temp_value = json_object_get_value(temp_object, temp_key);
1157                temp_value_copy = json_value_deep_copy(temp_value);
1158                if (temp_value_copy == NULL) {
1159                    json_value_free(return_value);
1160                    return NULL;
1161                }
1162                if (json_object_add(temp_object_copy, temp_key, temp_value_copy) == JSONFailure) {
1163                    json_value_free(return_value);
1164                    json_value_free(temp_value_copy);
1165                    return NULL;
1166                }
1167            }
1168            return return_value;
1169        case JSONBoolean:
1170            return json_value_init_boolean(json_value_get_boolean(value));
1171        case JSONNumber:
1172            return json_value_init_number(json_value_get_number(value));
1173        case JSONString:
1174            temp_string = json_value_get_string(value);
1175            temp_string_copy = parson_strdup(temp_string);
1176            if (temp_string_copy == NULL)
1177                return NULL;
1178            return_value = json_value_init_string_no_copy(temp_string_copy);
1179            if (return_value == NULL)
1180                PARSON_FREE(temp_string_copy);
1181            return return_value;
1182        case JSONNull:
1183            return json_value_init_null();
1184        case JSONError:
1185            return NULL;
1186        default:
1187            return NULL;
1188    }
1189}
1190
1191size_t json_serialization_size(const JSON_Value *value) {
1192    char buf[1100]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */
1193    return json_serialization_size_r(value, buf) + 1;
1194}
1195
1196JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) {
1197    char *serialization_result = NULL;
1198    size_t needed_size_in_bytes = json_serialization_size(value);
1199    if (buf_size_in_bytes < needed_size_in_bytes) {
1200        return JSONFailure;
1201    }
1202    serialization_result = json_serialize_to_buffer_r(value, buf);
1203    if(serialization_result == NULL)
1204        return JSONFailure;
1205    return JSONSuccess;
1206}
1207
1208JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename) {
1209    JSON_Status return_code = JSONSuccess;
1210    FILE *fp = NULL;
1211    char *serialized_string = json_serialize_to_string(value);
1212    if (serialized_string == NULL) {
1213        return JSONFailure;
1214    }
1215    fp = fopen (filename, "w");
1216    if (fp != NULL) {
1217        if (fputs (serialized_string, fp) == EOF) {
1218            return_code = JSONFailure;
1219        }
1220        if (fclose (fp) == EOF) {
1221            return_code = JSONFailure;
1222        }
1223    }
1224    json_free_serialized_string(serialized_string);
1225    return return_code;
1226}
1227
1228char * json_serialize_to_string(const JSON_Value *value) {
1229    JSON_Status serialization_result = JSONFailure;
1230    size_t buf_size_bytes = json_serialization_size(value);
1231    char *buf = (char*)PARSON_MALLOC(buf_size_bytes);
1232    if (buf == NULL)
1233        return NULL;
1234    serialization_result = json_serialize_to_buffer(value, buf, buf_size_bytes);
1235    if (serialization_result == JSONFailure) {
1236        json_free_serialized_string(buf);
1237        return NULL;
1238    }
1239    return buf;
1240}
1241
1242void json_free_serialized_string(char *string) {
1243    PARSON_FREE(string);
1244}
1245
1246JSON_Status json_array_remove(JSON_Array *array, size_t ix) {
1247    size_t last_element_ix = 0;
1248    if (array == NULL || ix >= json_array_get_count(array)) {
1249        return JSONFailure;
1250    }
1251    last_element_ix = json_array_get_count(array) - 1;
1252    json_value_free(json_array_get_value(array, ix));
1253    array->count -= 1;
1254    if (ix != last_element_ix) /* Replace value with one from the end of array */
1255        array->items[ix] = json_array_get_value(array, last_element_ix);
1256    return JSONSuccess;
1257}
1258
1259JSON_Status json_array_replace_value(JSON_Array *array, size_t ix, JSON_Value *value) {
1260    if (array == NULL || value == NULL || ix >= json_array_get_count(array)) {
1261        return JSONFailure;
1262    }
1263    json_value_free(json_array_get_value(array, ix));
1264    array->items[ix] = value;
1265    return JSONSuccess;
1266}
1267
1268JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string) {
1269    JSON_Value *value = json_value_init_string(string);
1270    if (value == NULL)
1271        return JSONFailure;
1272    if (json_array_replace_value(array, i, value) == JSONFailure) {
1273        json_value_free(value);
1274        return JSONFailure;
1275    }
1276    return JSONSuccess;
1277}
1278
1279JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number) {
1280    JSON_Value *value = json_value_init_number(number);
1281    if (value == NULL)
1282        return JSONFailure;
1283    if (json_array_replace_value(array, i, value) == JSONFailure) {
1284        json_value_free(value);
1285        return JSONFailure;
1286    }
1287    return JSONSuccess;
1288}
1289
1290JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean) {
1291    JSON_Value *value = json_value_init_boolean(boolean);
1292    if (value == NULL)
1293        return JSONFailure;
1294    if (json_array_replace_value(array, i, value) == JSONFailure) {
1295        json_value_free(value);
1296        return JSONFailure;
1297    }
1298    return JSONSuccess;
1299}
1300
1301JSON_Status json_array_replace_null(JSON_Array *array, size_t i) {
1302    JSON_Value *value = json_value_init_null();
1303    if (value == NULL)
1304        return JSONFailure;
1305    if (json_array_replace_value(array, i, value) == JSONFailure) {
1306        json_value_free(value);
1307        return JSONFailure;
1308    }
1309    return JSONSuccess;
1310}
1311
1312JSON_Status json_array_clear(JSON_Array *array) {
1313    size_t i = 0;
1314    if (array == NULL)
1315        return JSONFailure;
1316    for (i = 0; i < json_array_get_count(array); i++) {
1317        json_value_free(json_array_get_value(array, i));
1318    }
1319    array->count = 0;
1320    return JSONSuccess;
1321}
1322
1323JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value) {
1324    if (array == NULL || value == NULL)
1325        return JSONFailure;
1326    return json_array_add(array, value);
1327}
1328
1329JSON_Status json_array_append_string(JSON_Array *array, const char *string) {
1330    JSON_Value *value = json_value_init_string(string);
1331    if (value == NULL)
1332        return JSONFailure;
1333    if (json_array_append_value(array, value) == JSONFailure) {
1334        json_value_free(value);
1335        return JSONFailure;
1336    }
1337    return JSONSuccess;
1338}
1339
1340JSON_Status json_array_append_number(JSON_Array *array, double number) {
1341    JSON_Value *value = json_value_init_number(number);
1342    if (value == NULL)
1343        return JSONFailure;
1344    if (json_array_append_value(array, value) == JSONFailure) {
1345        json_value_free(value);
1346        return JSONFailure;
1347    }
1348    return JSONSuccess;
1349}
1350
1351JSON_Status json_array_append_boolean(JSON_Array *array, int boolean) {
1352    JSON_Value *value = json_value_init_boolean(boolean);
1353    if (value == NULL)
1354        return JSONFailure;
1355    if (json_array_append_value(array, value) == JSONFailure) {
1356        json_value_free(value);
1357        return JSONFailure;
1358    }
1359    return JSONSuccess;
1360}
1361
1362JSON_Status json_array_append_null(JSON_Array *array) {
1363    JSON_Value *value = json_value_init_null();
1364    if (value == NULL)
1365        return JSONFailure;
1366    if (json_array_append_value(array, value) == JSONFailure) {
1367        json_value_free(value);
1368        return JSONFailure;
1369    }
1370    return JSONSuccess;
1371}
1372
1373JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value) {
1374    size_t i = 0;
1375    JSON_Value *old_value;
1376    if (object == NULL || name == NULL || value == NULL)
1377        return JSONFailure;
1378    old_value = json_object_get_value(object, name);
1379    if (old_value != NULL) { /* free and overwrite old value */
1380        json_value_free(old_value);
1381        for (i = 0; i < json_object_get_count(object); i++) {
1382            if (strcmp(object->names[i], name) == 0) {
1383                object->values[i] = value;
1384                return JSONSuccess;
1385            }
1386        }
1387    }
1388    /* add new key value pair */
1389    return json_object_add(object, name, value);
1390}
1391
1392JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string) {
1393    return json_object_set_value(object, name, json_value_init_string(string));
1394}
1395
1396JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number) {
1397    return json_object_set_value(object, name, json_value_init_number(number));
1398}
1399
1400JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean) {
1401    return json_object_set_value(object, name, json_value_init_boolean(boolean));
1402}
1403
1404JSON_Status json_object_set_null(JSON_Object *object, const char *name) {
1405    return json_object_set_value(object, name, json_value_init_null());
1406}
1407
1408JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value) {
1409    const char *dot_pos = NULL;
1410    const char *current_name = NULL;
1411    JSON_Object *temp_obj = NULL;
1412    JSON_Value *new_value = NULL;
1413    if (value == NULL || name == NULL || value == NULL)
1414        return JSONFailure;
1415    dot_pos = strchr(name, '.');
1416    if (dot_pos == NULL) {
1417        return json_object_set_value(object, name, value);
1418    } else {
1419        current_name = parson_strndup(name, dot_pos - name);
1420        temp_obj = json_object_get_object(object, current_name);
1421        if (temp_obj == NULL) {
1422            new_value = json_value_init_object();
1423            if (new_value == NULL) {
1424                PARSON_FREE(current_name);
1425                return JSONFailure;
1426            }
1427            if (json_object_add(object, current_name, new_value) == JSONFailure) {
1428                json_value_free(new_value);
1429                PARSON_FREE(current_name);
1430                return JSONFailure;
1431            }
1432            temp_obj = json_object_get_object(object, current_name);
1433        }
1434        PARSON_FREE(current_name);
1435        return json_object_dotset_value(temp_obj, dot_pos + 1, value);
1436    }
1437}
1438
1439JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string) {
1440    JSON_Value *value = json_value_init_string(string);
1441    if (value == NULL)
1442        return JSONFailure;
1443    if (json_object_dotset_value(object, name, value) == JSONFailure) {
1444        json_value_free(value);
1445        return JSONFailure;
1446    }
1447    return JSONSuccess;
1448}
1449
1450JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number) {
1451    JSON_Value *value = json_value_init_number(number);
1452    if (value == NULL)
1453        return JSONFailure;
1454    if (json_object_dotset_value(object, name, value) == JSONFailure) {
1455        json_value_free(value);
1456        return JSONFailure;
1457    }
1458    return JSONSuccess;
1459}
1460
1461JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean) {
1462    JSON_Value *value = json_value_init_boolean(boolean);
1463    if (value == NULL)
1464        return JSONFailure;
1465    if (json_object_dotset_value(object, name, value) == JSONFailure) {
1466        json_value_free(value);
1467        return JSONFailure;
1468    }
1469    return JSONSuccess;
1470}
1471
1472JSON_Status json_object_dotset_null(JSON_Object *object, const char *name) {
1473    JSON_Value *value = json_value_init_null();
1474    if (value == NULL)
1475        return JSONFailure;
1476    if (json_object_dotset_value(object, name, value) == JSONFailure) {
1477        json_value_free(value);
1478        return JSONFailure;
1479    }
1480    return JSONSuccess;
1481}
1482
1483JSON_Status json_object_remove(JSON_Object *object, const char *name) {
1484    size_t i = 0, last_item_index = 0;
1485    if (object == NULL || json_object_get_value(object, name) == NULL)
1486        return JSONFailure;
1487    last_item_index = json_object_get_count(object) - 1;
1488    for (i = 0; i < json_object_get_count(object); i++) {
1489        if (strcmp(object->names[i], name) == 0) {
1490            PARSON_FREE(object->names[i]);
1491            json_value_free(object->values[i]);
1492            if (i != last_item_index) { /* Replace key value pair with one from the end */
1493                object->names[i] = object->names[last_item_index];
1494                object->values[i] = object->values[last_item_index];
1495            }
1496            object->count -= 1;
1497            return JSONSuccess;
1498        }
1499    }
1500    return JSONFailure; /* No execution path should end here */
1501}
1502
1503JSON_Status json_object_dotremove(JSON_Object *object, const char *name) {
1504    const char *dot_pos = strchr(name, '.');
1505    const char *current_name = NULL;
1506    JSON_Object *temp_obj = NULL;
1507    if (dot_pos == NULL) {
1508        return json_object_remove(object, name);
1509    } else {
1510        current_name = parson_strndup(name, dot_pos - name);
1511        temp_obj = json_object_get_object(object, current_name);
1512        if (temp_obj == NULL) {
1513            PARSON_FREE(current_name);
1514            return JSONFailure;
1515        }
1516        PARSON_FREE(current_name);
1517        return json_object_dotremove(temp_obj, dot_pos + 1);
1518    }
1519}
1520
1521JSON_Status json_object_clear(JSON_Object *object) {
1522    size_t i = 0;
1523    if (object == NULL) {
1524        return JSONFailure;
1525    }
1526    for (i = 0; i < json_object_get_count(object); i++) {       
1527        PARSON_FREE(object->names[i]);
1528        json_value_free(object->values[i]);
1529    }
1530    object->count = 0;
1531    return JSONSuccess;
1532}
1533
1534JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value) {
1535    JSON_Value *temp_schema_value = NULL, *temp_value = NULL;
1536    JSON_Array *schema_array = NULL, *value_array = NULL;
1537    JSON_Object *schema_object = NULL, *value_object = NULL;
1538    JSON_Value_Type schema_type = JSONError, value_type = JSONError;
1539    const char *key = NULL;
1540    size_t i = 0, count = 0;
1541    if (schema == NULL || value == NULL)
1542        return JSONFailure;
1543    schema_type = json_value_get_type(schema);
1544    value_type = json_value_get_type(value);
1545    if (schema_type != value_type && schema_type != JSONNull) /* null represents all values */
1546        return JSONFailure;
1547    switch (schema_type) {
1548        case JSONArray:
1549            schema_array = json_value_get_array(schema);
1550            value_array = json_value_get_array(value);
1551            count = json_array_get_count(schema_array);
1552            if (count == 0)
1553                return JSONSuccess; /* Empty array allows all types */
1554            /* Get first value from array, rest is ignored */
1555            temp_schema_value = json_array_get_value(schema_array, 0);
1556            for (i = 0; i < json_array_get_count(value_array); i++) {
1557                temp_value = json_array_get_value(value_array, i);
1558                if (json_validate(temp_schema_value, temp_value) == 0) {
1559                    return JSONFailure;
1560                }
1561            }
1562            return JSONSuccess;
1563        case JSONObject:
1564            schema_object = json_value_get_object(schema);
1565            value_object = json_value_get_object(value);
1566            count = json_object_get_count(schema_object);
1567            if (count == 0)
1568                return JSONSuccess; /* Empty object allows all objects */
1569            else if (json_object_get_count(value_object) < count)
1570                return JSONFailure; /* Tested object mustn't have less name-value pairs than schema */
1571            for (i = 0; i < count; i++) {
1572                key = json_object_get_name(schema_object, i);
1573                temp_schema_value = json_object_get_value(schema_object, key);
1574                temp_value = json_object_get_value(value_object, key);
1575                if (temp_value == NULL)
1576                    return JSONFailure;
1577                if (json_validate(temp_schema_value, temp_value) == JSONFailure)
1578                    return JSONFailure;
1579            }
1580            return JSONSuccess;
1581        case JSONString: case JSONNumber: case JSONBoolean: case JSONNull:
1582            return JSONSuccess; /* equality already tested before switch */
1583        case JSONError: default:
1584            return JSONFailure;
1585    }
1586}
1587
1588JSON_Status json_value_equals(const JSON_Value *a, const JSON_Value *b) {
1589    JSON_Object *a_object = NULL, *b_object = NULL;
1590    JSON_Array *a_array = NULL, *b_array = NULL;
1591    const char *a_string = NULL, *b_string = NULL;
1592    const char *key = NULL;
1593    size_t a_count = 0, b_count = 0, i = 0;
1594    JSON_Value_Type a_type, b_type;
1595    a_type = json_value_get_type(a);
1596    b_type = json_value_get_type(b);
1597    if (a_type != b_type) {
1598        return 0;
1599    }
1600    switch (a_type) {
1601        case JSONArray:
1602            a_array = json_value_get_array(a);
1603            b_array = json_value_get_array(b);
1604            a_count = json_array_get_count(a_array);
1605            b_count = json_array_get_count(b_array);
1606            if (a_count != b_count) {
1607                return 0;
1608            }
1609            for (i = 0; i < a_count; i++) {
1610                if (!json_value_equals(json_array_get_value(a_array, i),
1611                                       json_array_get_value(b_array, i))) {
1612                    return 0;
1613                }
1614            }
1615            return 1;
1616        case JSONObject:
1617            a_object = json_value_get_object(a);
1618            b_object = json_value_get_object(b);
1619            a_count = json_object_get_count(a_object);
1620            b_count = json_object_get_count(b_object);
1621            if (a_count != b_count) {
1622                return 0;
1623            }
1624            for (i = 0; i < a_count; i++) {
1625                key = json_object_get_name(a_object, i);
1626                if (!json_value_equals(json_object_get_value(a_object, key),
1627                                       json_object_get_value(b_object, key))) {
1628                    return 0;
1629                }
1630            }
1631            return 1;
1632        case JSONString:
1633            a_string = json_value_get_string(a);
1634            b_string = json_value_get_string(b);
1635            return strcmp(a_string, b_string) == 0;
1636        case JSONBoolean:
1637            return json_value_get_boolean(a) == json_value_get_boolean(b);
1638        case JSONNumber:
1639            return fabs(json_value_get_number(a) - json_value_get_number(b)) < 0.000001; /* EPSILON */
1640        case JSONError:
1641            return 1;
1642        case JSONNull:
1643            return 1;
1644        default:
1645            return 1;
1646    }
1647}
1648
1649JSON_Value_Type json_type(const JSON_Value *value) {
1650    return json_value_get_type(value);
1651}
1652
1653JSON_Object * json_object (const JSON_Value *value) {
1654    return json_value_get_object(value);
1655}
1656
1657JSON_Array * json_array  (const JSON_Value *value) {
1658    return json_value_get_array(value);
1659}
1660
1661const char * json_string (const JSON_Value *value) {
1662    return json_value_get_string(value);
1663}
1664
1665double json_number (const JSON_Value *value) {
1666    return json_value_get_number(value);
1667}
1668
1669int json_boolean(const JSON_Value *value) {
1670    return json_value_get_boolean(value);
1671}
Note: See TracBrowser for help on using the repository browser.