cJSON_Utils.c 39.2 KB
Newer Older
M
Max Bruckner 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

23 24 25 26
/* disable warnings about old C89 functions in MSVC */
#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
#define _CRT_SECURE_NO_DEPRECATE
#endif
27 28

#ifdef __GNUCC__
29
#pragma GCC visibility push(default)
30
#endif
31 32 33 34 35 36
#if defined(_MSC_VER)
#pragma warning (push)
/* disable warning about single line comments in system headers */
#pragma warning (disable : 4001)
#endif

37
#include <ctype.h>
38 39
#include <string.h>
#include <stdlib.h>
40
#include <stdio.h>
M
Max Bruckner 已提交
41
#include <limits.h>
42 43 44 45

#if defined(_MSC_VER)
#pragma warning (pop)
#endif
46
#ifdef __GNUCC__
47
#pragma GCC visibility pop
48
#endif
M
Max Bruckner 已提交
49

50 51
#include "cJSON_Utils.h"

M
Max Bruckner 已提交
52
/* define our own boolean type */
53 54 55
#ifdef true
#undef true
#endif
M
Max Bruckner 已提交
56
#define true ((cJSON_bool)1)
57 58 59 60

#ifdef false
#undef false
#endif
M
Max Bruckner 已提交
61 62
#define false ((cJSON_bool)0)

M
Max Bruckner 已提交
63
static unsigned char* cJSONUtils_strdup(const unsigned char* const string)
64
{
M
Max Bruckner 已提交
65
    size_t length = 0;
66
    unsigned char *copy = NULL;
67

M
Max Bruckner 已提交
68 69 70
    length = strlen((const char*)string) + sizeof("");
    copy = (unsigned char*) cJSON_malloc(length);
    if (copy == NULL)
71
    {
72
        return NULL;
73
    }
M
Max Bruckner 已提交
74
    memcpy(copy, string, length);
75 76 77 78

    return copy;
}

79 80
/* string comparison which doesn't consider NULL pointers equal */
static int compare_strings(const unsigned char *string1, const unsigned char *string2, const cJSON_bool case_sensitive)
81
{
M
Max Bruckner 已提交
82
    if ((string1 == NULL) || (string2 == NULL))
M
Max Bruckner 已提交
83
    {
M
Max Bruckner 已提交
84
        return 1;
M
Max Bruckner 已提交
85
    }
M
Max Bruckner 已提交
86 87

    if (string1 == string2)
M
Max Bruckner 已提交
88
    {
M
Max Bruckner 已提交
89
        return 0;
M
Max Bruckner 已提交
90
    }
M
Max Bruckner 已提交
91

92 93 94 95 96
    if (case_sensitive)
    {
        return strcmp((const char*)string1, (const char*)string2);
    }

M
Max Bruckner 已提交
97
    for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
M
Max Bruckner 已提交
98
    {
M
Max Bruckner 已提交
99
        if (*string1 == '\0')
M
Max Bruckner 已提交
100 101 102 103 104
        {
            return 0;
        }
    }

M
Max Bruckner 已提交
105
    return tolower(*string1) - tolower(*string2);
106 107
}

M
Max Bruckner 已提交
108
/* Compare the next path element of two JSON pointers, two NULL pointers are considered unequal: */
109
static cJSON_bool compare_pointers(const unsigned char *name, const unsigned char *pointer, const cJSON_bool case_sensitive)
110
{
M
Max Bruckner 已提交
111
    if ((name == NULL) || (pointer == NULL))
112
    {
113
        return false;
114
    }
M
Max Bruckner 已提交
115 116

    for (; (*name != '\0') && (*pointer != '\0') && (*pointer != '/'); (void)name++, pointer++) /* compare until next '/' */
117
    {
M
Max Bruckner 已提交
118
        if (*pointer == '~')
119 120
        {
            /* check for escaped '~' (~0) and '/' (~1) */
M
Max Bruckner 已提交
121
            if (((pointer[1] != '0') || (*name != '~')) && ((pointer[1] != '1') || (*name != '/')))
122
            {
M
Max Bruckner 已提交
123
                /* invalid escape sequence or wrong character in *name */
124
                return false;
125 126 127
            }
            else
            {
M
Max Bruckner 已提交
128
                pointer++;
129 130
            }
        }
131
        else if ((!case_sensitive && (tolower(*name) != tolower(*pointer))) || (case_sensitive && (*name != *pointer)))
132
        {
133
            return false;
134 135
        }
    }
M
Max Bruckner 已提交
136
    if (((*pointer != 0) && (*pointer != '/')) != (*name != 0))
137 138
    {
        /* one string has ended, the other not */
139
        return false;;
140 141
    }

142
    return true;
143 144
}

145
/* calculate the length of a string if encoded as JSON pointer with ~0 and ~1 escape sequences */
146
static size_t pointer_encoded_length(const unsigned char *string)
147
{
148 149
    size_t length;
    for (length = 0; *string != '\0'; (void)string++, length++)
150
    {
151 152
        /* character needs to be escaped? */
        if ((*string == '~') || (*string == '/'))
153
        {
154
            length++;
155 156 157
        }
    }

158
    return length;
159
}
160

161
/* copy a string while escaping '~' and '/' with ~0 and ~1 JSON pointer escape codes */
162
static void encode_string_as_pointer(unsigned char *destination, const unsigned char *source)
163
{
164
    for (; source[0] != '\0'; (void)source++, destination++)
165
    {
166
        if (source[0] == '/')
167
        {
168 169
            destination[1] = '1';
            destination++;
170
        }
171
        else if (source[0] == '~')
172
        {
173 174 175
            destination[0] = '~';
            destination[1] = '1';
            destination++;
176 177 178
        }
        else
        {
179
            destination[0] = source[0];
180 181 182
        }
    }

183
    destination[0] = '\0';
184 185
}

186
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target)
187
{
188 189
    size_t child_index = 0;
    cJSON *current_child = 0;
190

191 192 193 194 195
    if ((object == NULL) || (target == NULL))
    {
        return NULL;
    }

196 197 198
    if (object == target)
    {
        /* found */
199
        return (char*)cJSONUtils_strdup((const unsigned char*)"");
200
    }
201

202 203
    /* recursively search all children of the object or array */
    for (current_child = object->child; current_child != NULL; (void)(current_child = current_child->next), child_index++)
204
    {
205 206 207
        unsigned char *target_pointer = (unsigned char*)cJSONUtils_FindPointerFromObjectTo(current_child, target);
        /* found the target? */
        if (target_pointer != NULL)
208
        {
209
            if (cJSON_IsArray(object))
210 211
            {
                /* reserve enough memory for a 64 bit integer + '/' and '\0' */
212
                unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + 20 + sizeof("/"));
213 214 215
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
216
                if (child_index > ULONG_MAX)
217
                {
218
                    cJSON_free(target_pointer);
219 220
                    return NULL;
                }
221 222
                sprintf((char*)full_pointer, "/%lu%s", (unsigned long)child_index, target_pointer); /* /<array_index><path> */
                cJSON_free(target_pointer);
223

224
                return (char*)full_pointer;
225
            }
226 227

            if (cJSON_IsObject(object))
228
            {
229
                unsigned char *full_pointer = (unsigned char*)cJSON_malloc(strlen((char*)target_pointer) + pointer_encoded_length((unsigned char*)current_child->string) + 2);
230
                full_pointer[0] = '/';
231
                encode_string_as_pointer(full_pointer + 1, (unsigned char*)current_child->string);
232 233
                strcat((char*)full_pointer, (char*)target_pointer);
                cJSON_free(target_pointer);
234

235
                return (char*)full_pointer;
236 237 238
            }

            /* reached leaf of the tree, found nothing */
239
            cJSON_free(target_pointer);
240
            return NULL;
241 242 243 244
        }
    }

    /* not found */
245
    return NULL;
246 247
}

248 249 250 251 252 253 254 255 256 257 258 259 260
/* non broken version of cJSON_GetArrayItem */
static cJSON *get_array_item(const cJSON *array, size_t item)
{
    cJSON *child = array ? array->child : NULL;
    while ((child != NULL) && (item > 0))
    {
        item--;
        child = child->next;
    }

    return child;
}

261 262 263 264 265 266 267 268 269 270 271
static cJSON_bool decode_array_index_from_pointer(const unsigned char * const pointer, size_t * const index)
{
    size_t parsed_index = 0;
    size_t position = 0;

    if ((pointer[0] == '0') && ((pointer[1] != '\0') && (pointer[1] != '/')))
    {
        /* leading zeroes are not permitted */
        return 0;
    }

272
    for (position = 0; (pointer[position] >= '0') && (pointer[0] <= '9'); position++)
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    {
        parsed_index = (10 * parsed_index) + (size_t)(pointer[position] - '0');

    }

    if ((pointer[position] != '\0') && (pointer[position] != '/'))
    {
        return 0;
    }

    *index = parsed_index;

    return 1;
}

288
static cJSON *get_item_from_pointer(cJSON * const object, const char * pointer, const cJSON_bool case_sensitive)
289
{
M
Max Bruckner 已提交
290
    cJSON *current_element = object;
291 292 293 294 295 296

    if (pointer == NULL)
    {
        return NULL;
    }

297
    /* follow path of the pointer */
M
Max Bruckner 已提交
298
    while ((pointer[0] == '/') && (current_element != NULL))
299
    {
M
Max Bruckner 已提交
300 301
        pointer++;
        if (cJSON_IsArray(current_element))
302
        {
303
            size_t index = 0;
304
            if (!decode_array_index_from_pointer((const unsigned char*)pointer, &index))
305
            {
306
                return NULL;
307
            }
308

M
Max Bruckner 已提交
309
            current_element = get_array_item(current_element, index);
310
        }
M
Max Bruckner 已提交
311
        else if (cJSON_IsObject(current_element))
312
        {
M
Max Bruckner 已提交
313
            current_element = current_element->child;
314
            /* GetObjectItem. */
315
            while ((current_element != NULL) && !compare_pointers((unsigned char*)current_element->string, (const unsigned char*)pointer, case_sensitive))
316
            {
M
Max Bruckner 已提交
317
                current_element = current_element->next;
318 319 320 321
            }
        }
        else
        {
322
            return NULL;
323
        }
324 325 326 327 328 329

        /* skip to the next path token or end of string */
        while ((pointer[0] != '\0') && (pointer[0] != '/'))
        {
            pointer++;
        }
330 331
    }

M
Max Bruckner 已提交
332
    return current_element;
333 334
}

335 336 337 338 339
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer)
{
    return get_item_from_pointer(object, pointer, false);
}

340 341 342 343 344
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer)
{
    return get_item_from_pointer(object, pointer, true);
}

345
/* JSON Patch implementation. */
346
static void decode_pointer_inplace(unsigned char *string)
347
{
348
    unsigned char *decoded_string = string;
349 350 351 352 353

    if (string == NULL) {
        return;
    }

354
    for (; *string; (void)decoded_string++, string++)
355
    {
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
        if (string[0] == '~')
        {
            if (string[1] == '0')
            {
                decoded_string[0] = '~';
            }
            else if (string[1] == '1')
            {
                decoded_string[1] = '/';
            }
            else
            {
                /* invalid escape sequence */
                return;
            }

            string++;
        }
374 375
    }

376
    decoded_string[0] = '\0';
377 378
}

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
/* non-broken cJSON_DetachItemFromArray */
static cJSON *detach_item_from_array(cJSON *array, size_t which)
{
    cJSON *c = array->child;
    while (c && (which > 0))
    {
        c = c->next;
        which--;
    }
    if (!c)
    {
        /* item doesn't exist */
        return NULL;
    }
    if (c->prev)
    {
        /* not the first element */
        c->prev->next = c->next;
    }
    if (c->next)
    {
        c->next->prev = c->prev;
    }
    if (c==array->child)
    {
        array->child = c->next;
    }
    /* make sure the detached item doesn't point anywhere anymore */
    c->prev = c->next = NULL;

    return c;
}

412
/* detach an item at the given path */
413
static cJSON *detach_path(cJSON *object, const unsigned char *path, const cJSON_bool case_sensitive)
414
{
M
Max Bruckner 已提交
415 416
    unsigned char *parent_pointer = NULL;
    unsigned char *child_pointer = NULL;
417
    cJSON *parent = NULL;
M
Max Bruckner 已提交
418
    cJSON *detached_item = NULL;
419 420

    /* copy path and split it in parent and child */
M
Max Bruckner 已提交
421 422 423
    parent_pointer = cJSONUtils_strdup(path);
    if (parent_pointer == NULL) {
        goto cleanup;
424 425
    }

M
Max Bruckner 已提交
426 427
    child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/'); /* last '/' */
    if (child_pointer == NULL)
428
    {
M
Max Bruckner 已提交
429
        goto cleanup;
430
    }
431
    /* split strings */
M
Max Bruckner 已提交
432 433
    child_pointer[0] = '\0';
    child_pointer++;
434

435
    parent = get_item_from_pointer(object, (char*)parent_pointer, case_sensitive);
436
    decode_pointer_inplace(child_pointer);
437

M
Max Bruckner 已提交
438
    if (cJSON_IsArray(parent))
439
    {
440
        size_t index = 0;
M
Max Bruckner 已提交
441
        if (!decode_array_index_from_pointer(child_pointer, &index))
442
        {
M
Max Bruckner 已提交
443
            goto cleanup;
444
        }
M
Max Bruckner 已提交
445
        detached_item = detach_item_from_array(parent, index);
446
    }
447
    else if (cJSON_IsObject(parent))
448
    {
M
Max Bruckner 已提交
449 450 451 452 453 454 455 456 457 458 459 460
        detached_item = cJSON_DetachItemFromObject(parent, (char*)child_pointer);
    }
    else
    {
        /* Couldn't find object to remove child from. */
        goto cleanup;
    }

cleanup:
    if (parent_pointer != NULL)
    {
        cJSON_free(parent_pointer);
461
    }
462

M
Max Bruckner 已提交
463
    return detached_item;
464 465
}

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
/* sort lists using mergesort */
static cJSON *sort_list(cJSON *list, const cJSON_bool case_sensitive)
{
    cJSON *first = list;
    cJSON *second = list;
    cJSON *current_item = list;
    cJSON *result = list;
    cJSON *result_tail = NULL;

    if ((list == NULL) || (list->next == NULL))
    {
        /* One entry is sorted already. */
        return result;
    }

    while ((current_item != NULL) && (current_item->next != NULL) && (compare_strings((unsigned char*)current_item->string, (unsigned char*)current_item->next->string, case_sensitive) < 0))
    {
        /* Test for list sorted. */
        current_item = current_item->next;
    }
    if ((current_item == NULL) || (current_item->next == NULL))
    {
        /* Leave sorted lists unmodified. */
        return result;
    }

    /* reset pointer to the beginning */
    current_item = list;
    while (current_item != NULL)
    {
        /* Walk two pointers to find the middle. */
        second = second->next;
        current_item = current_item->next;
        /* advances current_item two steps at a time */
        if (current_item != NULL)
        {
            current_item = current_item->next;
        }
    }
    if ((second != NULL) && (second->prev != NULL))
    {
        /* Split the lists */
        second->prev->next = NULL;
509
        second->prev = NULL;
510 511 512 513 514 515 516 517 518 519 520
    }

    /* Recursively sort the sub-lists. */
    first = sort_list(first, case_sensitive);
    second = sort_list(second, case_sensitive);
    result = NULL;

    /* Merge the sub-lists */
    while ((first != NULL) && (second != NULL))
    {
        cJSON *smaller = NULL;
521
        if (compare_strings((unsigned char*)first->string, (unsigned char*)second->string, case_sensitive) < 0)
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
        {
            smaller = first;
        }
        else
        {
            smaller = second;
        }

        if (result == NULL)
        {
            /* start merged list with the smaller element */
            result_tail = smaller;
            result = smaller;
        }
        else
        {
            /* add smaller element to the list */
            result_tail->next = smaller;
            smaller->prev = result_tail;
            result_tail = smaller;
        }

        if (first == smaller)
        {
            first = first->next;
        }
        else
        {
            second = second->next;
        }
    }

    if (first != NULL)
    {
        /* Append rest of first list. */
        if (result == NULL)
        {
            return first;
        }
        result_tail->next = first;
        first->prev = result_tail;
    }
    if (second != NULL)
    {
        /* Append rest of second list */
        if (result == NULL)
        {
            return second;
        }
        result_tail->next = second;
        second->prev = result_tail;
    }

    return result;
}

static void sort_object(cJSON * const object, const cJSON_bool case_sensitive)
{
M
Max Bruckner 已提交
580 581 582 583
    if (object == NULL)
    {
        return;
    }
584 585 586
    object->child = sort_list(object->child, case_sensitive);
}

587
static cJSON_bool compare_json(cJSON *a, cJSON *b, const cJSON_bool case_sensitive)
588
{
589
    if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)))
M
Max Bruckner 已提交
590 591
    {
        /* mismatched type. */
592
        return false;
M
Max Bruckner 已提交
593
    }
594
    switch (a->type & 0xFF)
M
Max Bruckner 已提交
595 596 597
    {
        case cJSON_Number:
            /* numeric mismatch. */
M
Max Bruckner 已提交
598 599
            if ((a->valueint != b->valueint) || (a->valuedouble != b->valuedouble))
            {
600
                return false;
M
Max Bruckner 已提交
601 602 603
            }
            else
            {
604
                return true;
M
Max Bruckner 已提交
605 606
            }

M
Max Bruckner 已提交
607 608
        case cJSON_String:
            /* string mismatch. */
M
Max Bruckner 已提交
609
            if (strcmp(a->valuestring, b->valuestring) != 0)
M
Max Bruckner 已提交
610
            {
611
                return false;
M
Max Bruckner 已提交
612 613 614
            }
            else
            {
615
                return true;
M
Max Bruckner 已提交
616 617
            }

M
Max Bruckner 已提交
618
        case cJSON_Array:
M
Max Bruckner 已提交
619
            for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next)
M
Max Bruckner 已提交
620
            {
621
                cJSON_bool identical = compare_json(a, b, case_sensitive);
622
                if (!identical)
M
Max Bruckner 已提交
623
                {
624
                    return false;
M
Max Bruckner 已提交
625 626
                }
            }
M
Max Bruckner 已提交
627

M
Max Bruckner 已提交
628
            /* array size mismatch? (one of both children is not NULL) */
M
Max Bruckner 已提交
629 630
            if ((a != NULL) || (b != NULL))
            {
631
                return false;
M
Max Bruckner 已提交
632 633 634
            }
            else
            {
635
                return true;
M
Max Bruckner 已提交
636 637
            }

M
Max Bruckner 已提交
638
        case cJSON_Object:
639 640
            sort_object(a, case_sensitive);
            sort_object(b, case_sensitive);
M
Max Bruckner 已提交
641
            for ((void)(a = a->child), b = b->child; (a != NULL) && (b != NULL); (void)(a = a->next), b = b->next)
M
Max Bruckner 已提交
642
            {
643
                cJSON_bool identical = false;
M
Max Bruckner 已提交
644
                /* compare object keys */
645
                if (compare_strings((unsigned char*)a->string, (unsigned char*)b->string, case_sensitive))
M
Max Bruckner 已提交
646 647
                {
                    /* missing member */
648
                    return false;
M
Max Bruckner 已提交
649
                }
650
                identical = compare_json(a, b, case_sensitive);
651
                if (!identical)
M
Max Bruckner 已提交
652
                {
653
                    return false;
M
Max Bruckner 已提交
654 655
                }
            }
M
Max Bruckner 已提交
656

M
Max Bruckner 已提交
657
            /* object length mismatch (one of both children is not null) */
M
Max Bruckner 已提交
658 659
            if ((a != NULL) || (b != NULL))
            {
660
                return false;
M
Max Bruckner 已提交
661 662 663
            }
            else
            {
664
                return true;
M
Max Bruckner 已提交
665
            }
666

M
Max Bruckner 已提交
667 668 669
        default:
            break;
    }
M
Max Bruckner 已提交
670

M
Max Bruckner 已提交
671
    /* null, true or false */
672
    return true;
673 674
}

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
/* non broken version of cJSON_InsertItemInArray */
static cJSON_bool insert_item_in_array(cJSON *array, size_t which, cJSON *newitem)
{
    cJSON *child = array->child;
    while (child && (which > 0))
    {
        child = child->next;
        which--;
    }
    if (which > 0)
    {
        /* item is after the end of the array */
        return 0;
    }
    if (child == NULL)
    {
        cJSON_AddItemToArray(array, newitem);
        return 1;
    }

    /* insert into the linked list */
    newitem->next = child;
    newitem->prev = child->prev;
    child->prev = newitem;

    /* was it at the beginning */
    if (child == array->child)
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }

    return 1;
}

713 714 715 716 717 718 719 720 721 722
static cJSON *get_object_item(const cJSON * const object, const char* name, const cJSON_bool case_sensitive)
{
    if (case_sensitive)
    {
        return cJSON_GetObjectItemCaseSensitive(object, name);
    }

    return cJSON_GetObjectItem(object, name);
}

M
Max Bruckner 已提交
723 724
enum patch_operation { INVALID, ADD, REMOVE, REPLACE, MOVE, COPY, TEST };

725
static enum patch_operation decode_patch_operation(const cJSON * const patch, const cJSON_bool case_sensitive)
726
{
727
    cJSON *operation = get_object_item(patch, "op", case_sensitive);
M
Max Bruckner 已提交
728 729 730 731
    if (!cJSON_IsString(operation))
    {
        return INVALID;
    }
732

M
Max Bruckner 已提交
733
    if (strcmp(operation->valuestring, "add") == 0)
M
Max Bruckner 已提交
734
    {
M
Max Bruckner 已提交
735
        return ADD;
M
Max Bruckner 已提交
736
    }
737

M
Max Bruckner 已提交
738
    if (strcmp(operation->valuestring, "remove") == 0)
M
Max Bruckner 已提交
739
    {
M
Max Bruckner 已提交
740
        return REMOVE;
M
Max Bruckner 已提交
741
    }
M
Max Bruckner 已提交
742 743

    if (strcmp(operation->valuestring, "replace") == 0)
M
Max Bruckner 已提交
744
    {
M
Max Bruckner 已提交
745
        return REPLACE;
M
Max Bruckner 已提交
746
    }
M
Max Bruckner 已提交
747 748

    if (strcmp(operation->valuestring, "move") == 0)
M
Max Bruckner 已提交
749
    {
M
Max Bruckner 已提交
750
        return MOVE;
M
Max Bruckner 已提交
751
    }
M
Max Bruckner 已提交
752 753

    if (strcmp(operation->valuestring, "copy") == 0)
M
Max Bruckner 已提交
754
    {
M
Max Bruckner 已提交
755
        return COPY;
M
Max Bruckner 已提交
756
    }
M
Max Bruckner 已提交
757 758

    if (strcmp(operation->valuestring, "test") == 0)
M
Max Bruckner 已提交
759
    {
M
Max Bruckner 已提交
760
        return TEST;
M
Max Bruckner 已提交
761
    }
M
Max Bruckner 已提交
762 763 764 765 766 767 768 769

    return INVALID;
}

/* overwrite and existing item with another one and free resources on the way */
static void overwrite_item(cJSON * const root, const cJSON replacement)
{
    if (root == NULL)
M
Max Bruckner 已提交
770
    {
M
Max Bruckner 已提交
771
        return;
M
Max Bruckner 已提交
772
    }
M
Max Bruckner 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789

    if (root->string != NULL)
    {
        cJSON_free(root->string);
    }
    if (root->valuestring != NULL)
    {
        cJSON_free(root->valuestring);
    }
    if (root->child != NULL)
    {
        cJSON_Delete(root->child);
    }

    memcpy(root, &replacement, sizeof(cJSON));
}

790
static int apply_patch(cJSON *object, const cJSON *patch, const cJSON_bool case_sensitive)
M
Max Bruckner 已提交
791 792 793 794 795 796 797 798 799
{
    cJSON *path = NULL;
    cJSON *value = NULL;
    cJSON *parent = NULL;
    enum patch_operation opcode = INVALID;
    unsigned char *parent_pointer = NULL;
    unsigned char *child_pointer = NULL;
    int status = 0;

800
    path = get_object_item(patch, "path", case_sensitive);
M
Max Bruckner 已提交
801
    if (!cJSON_IsString(path))
M
Max Bruckner 已提交
802
    {
M
Max Bruckner 已提交
803 804 805 806 807
        /* malformed patch. */
        status = 2;
        goto cleanup;
    }

808
    opcode = decode_patch_operation(patch, case_sensitive);
M
Max Bruckner 已提交
809 810 811 812 813 814 815 816
    if (opcode == INVALID)
    {
        status = 3;
        goto cleanup;
    }
    else if (opcode == TEST)
    {
        /* compare value: {...} with the given path */
817
        status = !compare_json(get_item_from_pointer(object, path->valuestring, case_sensitive), get_object_item(patch, "value", case_sensitive), case_sensitive);
M
Max Bruckner 已提交
818
        goto cleanup;
M
Max Bruckner 已提交
819
    }
820

821 822 823 824 825
    /* special case for replacing the root */
    if (path->valuestring[0] == '\0')
    {
        if (opcode == REMOVE)
        {
M
Max Bruckner 已提交
826
            static const cJSON invalid = { NULL, NULL, NULL, cJSON_Invalid, NULL, 0, 0, NULL};
827

M
Max Bruckner 已提交
828
            overwrite_item(object, invalid);
829

M
Max Bruckner 已提交
830 831
            status = 0;
            goto cleanup;
832 833 834 835
        }

        if ((opcode == REPLACE) || (opcode == ADD))
        {
836
            value = get_object_item(patch, "value", case_sensitive);
837 838 839
            if (value == NULL)
            {
                /* missing "value" for add/replace. */
M
Max Bruckner 已提交
840 841
                status = 7;
                goto cleanup;
842 843 844 845 846 847
            }

            value = cJSON_Duplicate(value, 1);
            if (value == NULL)
            {
                /* out of memory for add/replace. */
M
Max Bruckner 已提交
848 849
                status = 8;
                goto cleanup;
850 851
            }

M
Max Bruckner 已提交
852
            overwrite_item(object, *value);
853 854 855

            /* delete the duplicated value */
            cJSON_free(value);
M
Max Bruckner 已提交
856
            value = NULL;
857

M
Max Bruckner 已提交
858 859 860 861 862 863 864 865 866
            /* the string "value" isn't needed */
            if (object->string != NULL)
            {
                cJSON_free(object->string);
                object->string = NULL;
            }

            status = 0;
            goto cleanup;
867 868 869
        }
    }

M
Max Bruckner 已提交
870
    if ((opcode == REMOVE) || (opcode == REPLACE))
M
Max Bruckner 已提交
871 872
    {
        /* Get rid of old. */
873
        cJSON *old_item = detach_path(object, (unsigned char*)path->valuestring, case_sensitive);
874 875
        if (old_item == NULL)
        {
M
Max Bruckner 已提交
876 877
            status = 13;
            goto cleanup;
878 879
        }
        cJSON_Delete(old_item);
M
Max Bruckner 已提交
880
        if (opcode == REMOVE)
M
Max Bruckner 已提交
881
        {
882
            /* For Remove, this job is done. */
M
Max Bruckner 已提交
883 884
            status = 0;
            goto cleanup;
M
Max Bruckner 已提交
885 886
        }
    }
887

M
Max Bruckner 已提交
888
    /* Copy/Move uses "from". */
M
Max Bruckner 已提交
889
    if ((opcode == MOVE) || (opcode == COPY))
M
Max Bruckner 已提交
890
    {
891
        cJSON *from = get_object_item(patch, "from", case_sensitive);
M
Max Bruckner 已提交
892
        if (from == NULL)
M
Max Bruckner 已提交
893 894
        {
            /* missing "from" for copy/move. */
M
Max Bruckner 已提交
895 896
            status = 4;
            goto cleanup;
M
Max Bruckner 已提交
897
        }
898

M
Max Bruckner 已提交
899
        if (opcode == MOVE)
M
Max Bruckner 已提交
900
        {
901
            value = detach_path(object, (unsigned char*)from->valuestring, case_sensitive);
M
Max Bruckner 已提交
902
        }
M
Max Bruckner 已提交
903
        if (opcode == COPY)
M
Max Bruckner 已提交
904
        {
905
            value = get_item_from_pointer(object, from->valuestring, case_sensitive);
M
Max Bruckner 已提交
906
        }
M
Max Bruckner 已提交
907
        if (value == NULL)
M
Max Bruckner 已提交
908 909
        {
            /* missing "from" for copy/move. */
M
Max Bruckner 已提交
910 911
            status = 5;
            goto cleanup;
M
Max Bruckner 已提交
912
        }
M
Max Bruckner 已提交
913
        if (opcode == COPY)
M
Max Bruckner 已提交
914 915 916
        {
            value = cJSON_Duplicate(value, 1);
        }
M
Max Bruckner 已提交
917
        if (value == NULL)
M
Max Bruckner 已提交
918 919
        {
            /* out of memory for copy/move. */
M
Max Bruckner 已提交
920 921
            status = 6;
            goto cleanup;
M
Max Bruckner 已提交
922 923 924 925
        }
    }
    else /* Add/Replace uses "value". */
    {
926
        value = get_object_item(patch, "value", case_sensitive);
M
Max Bruckner 已提交
927
        if (value == NULL)
M
Max Bruckner 已提交
928 929
        {
            /* missing "value" for add/replace. */
M
Max Bruckner 已提交
930 931
            status = 7;
            goto cleanup;
M
Max Bruckner 已提交
932 933
        }
        value = cJSON_Duplicate(value, 1);
M
Max Bruckner 已提交
934
        if (value == NULL)
M
Max Bruckner 已提交
935 936
        {
            /* out of memory for add/replace. */
M
Max Bruckner 已提交
937 938
            status = 8;
            goto cleanup;
M
Max Bruckner 已提交
939 940
        }
    }
941

M
Max Bruckner 已提交
942
    /* Now, just add "value" to "path". */
943

M
Max Bruckner 已提交
944
    /* split pointer in parent and child */
M
Max Bruckner 已提交
945 946 947
    parent_pointer = cJSONUtils_strdup((unsigned char*)path->valuestring);
    child_pointer = (unsigned char*)strrchr((char*)parent_pointer, '/');
    if (child_pointer != NULL)
M
Max Bruckner 已提交
948
    {
M
Max Bruckner 已提交
949 950
        child_pointer[0] = '\0';
        child_pointer++;
M
Max Bruckner 已提交
951
    }
952
    parent = get_item_from_pointer(object, (char*)parent_pointer, case_sensitive);
953
    decode_pointer_inplace(child_pointer);
954

M
Max Bruckner 已提交
955
    /* add, remove, replace, move, copy, test. */
M
Max Bruckner 已提交
956
    if ((parent == NULL) || (child_pointer == NULL))
M
Max Bruckner 已提交
957 958
    {
        /* Couldn't find object to add to. */
M
Max Bruckner 已提交
959 960
        status = 9;
        goto cleanup;
M
Max Bruckner 已提交
961
    }
962
    else if (cJSON_IsArray(parent))
M
Max Bruckner 已提交
963
    {
M
Max Bruckner 已提交
964
        if (strcmp((char*)child_pointer, "-") == 0)
M
Max Bruckner 已提交
965 966
        {
            cJSON_AddItemToArray(parent, value);
M
Max Bruckner 已提交
967
            value = NULL;
M
Max Bruckner 已提交
968 969 970
        }
        else
        {
971
            size_t index = 0;
M
Max Bruckner 已提交
972
            if (!decode_array_index_from_pointer(child_pointer, &index))
973
            {
M
Max Bruckner 已提交
974 975
                status = 11;
                goto cleanup;
976 977
            }

978
            if (!insert_item_in_array(parent, index, value))
979
            {
M
Max Bruckner 已提交
980 981
                status = 10;
                goto cleanup;
982
            }
M
Max Bruckner 已提交
983
            value = NULL;
M
Max Bruckner 已提交
984 985
        }
    }
986
    else if (cJSON_IsObject(parent))
M
Max Bruckner 已提交
987
    {
988 989 990 991 992 993 994 995
        if (case_sensitive)
        {
            cJSON_DeleteItemFromObjectCaseSensitive(parent, (char*)child_pointer);
        }
        else
        {
            cJSON_DeleteItemFromObject(parent, (char*)child_pointer);
        }
M
Max Bruckner 已提交
996 997
        cJSON_AddItemToObject(parent, (char*)child_pointer, value);
        value = NULL;
M
Max Bruckner 已提交
998
    }
999 1000 1001 1002 1003 1004
    else /* parent is not an object */
    {
        /* Couldn't find object to add to. */
        status = 9;
        goto cleanup;
    }
M
Max Bruckner 已提交
1005 1006 1007

cleanup:
    if (value != NULL)
M
Max Bruckner 已提交
1008 1009 1010
    {
        cJSON_Delete(value);
    }
M
Max Bruckner 已提交
1011 1012 1013 1014
    if (parent_pointer != NULL)
    {
        cJSON_free(parent_pointer);
    }
M
Max Bruckner 已提交
1015

M
Max Bruckner 已提交
1016
    return status;
M
Max Bruckner 已提交
1017
}
1018

M
Max Bruckner 已提交
1019
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches)
1020
{
M
Max Bruckner 已提交
1021 1022
    const cJSON *current_patch = NULL;
    int status = 0;
1023

1024
    if (!cJSON_IsArray(patches))
1025 1026 1027 1028
    {
        /* malformed patches. */
        return 1;
    }
M
Max Bruckner 已提交
1029 1030

    if (patches != NULL)
1031
    {
M
Max Bruckner 已提交
1032
        current_patch = patches->child;
1033
    }
M
Max Bruckner 已提交
1034 1035

    while (current_patch != NULL)
1036
    {
1037
        status = apply_patch(object, current_patch, false);
M
Max Bruckner 已提交
1038
        if (status != 0)
1039
        {
M
Max Bruckner 已提交
1040
            return status;
1041
        }
M
Max Bruckner 已提交
1042
        current_patch = current_patch->next;
1043 1044 1045
    }

    return 0;
1046
}
1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches)
{
    const cJSON *current_patch = NULL;
    int status = 0;

    if (!cJSON_IsArray(patches))
    {
        /* malformed patches. */
        return 1;
    }

    if (patches != NULL)
    {
        current_patch = patches->child;
    }

    while (current_patch != NULL)
    {
        status = apply_patch(object, current_patch, true);
        if (status != 0)
        {
            return status;
        }
        current_patch = current_patch->next;
    }

    return 0;
}

1077
static void compose_patch(cJSON * const patches, const unsigned char * const operation, const unsigned char * const path, const unsigned char *suffix, const cJSON * const value)
1078
{
1079 1080 1081 1082 1083 1084 1085 1086
    cJSON *patch = NULL;

    if ((patches == NULL) || (operation == NULL) || (path == NULL))
    {
        return;
    }

    patch = cJSON_CreateObject();
M
Max Bruckner 已提交
1087
    if (patch == NULL)
1088
    {
M
Max Bruckner 已提交
1089
        return;
1090
    }
M
Max Bruckner 已提交
1091 1092 1093
    cJSON_AddItemToObject(patch, "op", cJSON_CreateString((const char*)operation));

    if (suffix == NULL)
1094
    {
1095
        cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)path));
1096
    }
M
Max Bruckner 已提交
1097 1098
    else
    {
1099
        size_t suffix_length = pointer_encoded_length(suffix);
M
Max Bruckner 已提交
1100 1101 1102 1103
        size_t path_length = strlen((const char*)path);
        unsigned char *full_path = (unsigned char*)cJSON_malloc(path_length + suffix_length + sizeof("/"));

        sprintf((char*)full_path, "%s/", (const char*)path);
1104
        encode_string_as_pointer(full_path + path_length + 1, suffix);
M
Max Bruckner 已提交
1105 1106

        cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)full_path));
C
crhackos 已提交
1107
        cJSON_free(full_path);
M
Max Bruckner 已提交
1108 1109 1110
    }

    if (value != NULL)
1111
    {
M
Max Bruckner 已提交
1112
        cJSON_AddItemToObject(patch, "value", cJSON_Duplicate(value, 1));
1113 1114
    }
    cJSON_AddItemToArray(patches, patch);
1115 1116
}

1117
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value)
M
Max Bruckner 已提交
1118
{
1119
    compose_patch(array, (const unsigned char*)operation, (const unsigned char*)path, NULL, value);
M
Max Bruckner 已提交
1120
}
1121

1122
static void create_patches(cJSON * const patches, const unsigned char * const path, cJSON * const from, cJSON * const to, const cJSON_bool case_sensitive)
1123
{
1124 1125 1126 1127 1128
    if ((from == NULL) || (to == NULL))
    {
        return;
    }

1129
    if ((from->type & 0xFF) != (to->type & 0xFF))
1130
    {
1131
        compose_patch(patches, (const unsigned char*)"replace", path, 0, to);
1132 1133 1134
        return;
    }

1135
    switch (from->type & 0xFF)
1136 1137 1138 1139
    {
        case cJSON_Number:
            if ((from->valueint != to->valueint) || (from->valuedouble != to->valuedouble))
            {
1140
                compose_patch(patches, (const unsigned char*)"replace", path, NULL, to);
1141 1142 1143 1144
            }
            return;

        case cJSON_String:
M
Max Bruckner 已提交
1145
            if (strcmp(from->valuestring, to->valuestring) != 0)
1146
            {
1147
                compose_patch(patches, (const unsigned char*)"replace", path, NULL, to);
1148 1149
            }
            return;
1150

1151 1152
        case cJSON_Array:
        {
1153 1154 1155 1156 1157 1158 1159
            size_t index = 0;
            cJSON *from_child = from->child;
            cJSON *to_child = to->child;
            unsigned char *new_path = (unsigned char*)cJSON_malloc(strlen((const char*)path) + 20 + sizeof("/")); /* Allow space for 64bit int. log10(2^64) = 20 */

            /* generate patches for all array elements that exist in both "from" and "to" */
            for (index = 0; (from_child != NULL) && (to_child != NULL); (void)(from_child = from_child->next), (void)(to_child = to_child->next), index++)
1160
            {
1161 1162 1163
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
1164
                if (index > ULONG_MAX)
1165
                {
C
crhackos 已提交
1166
                    cJSON_free(new_path);
1167 1168
                    return;
                }
1169
                sprintf((char*)new_path, "%s/%lu", path, (unsigned long)index); /* path of the current array element */
1170
                create_patches(patches, new_path, from_child, to_child, case_sensitive);
1171
            }
1172

1173
            /* remove leftover elements from 'from' that are not in 'to' */
1174
            for (; (from_child != NULL); (void)(from_child = from_child->next))
1175
            {
1176 1177 1178
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
1179
                if (index > ULONG_MAX)
1180
                {
C
crhackos 已提交
1181
                    cJSON_free(new_path);
1182 1183
                    return;
                }
1184
                sprintf((char*)new_path, "%lu", (unsigned long)index);
1185
                compose_patch(patches, (const unsigned char*)"remove", path, new_path, NULL);
1186 1187
            }
            /* add new elements in 'to' that were not in 'from' */
1188
            for (; (to_child != NULL); (void)(to_child = to_child->next), index++)
1189
            {
1190
                compose_patch(patches, (const unsigned char*)"add", path, (const unsigned char*)"-", to_child);
1191
            }
C
crhackos 已提交
1192
            cJSON_free(new_path);
1193 1194 1195 1196 1197
            return;
        }

        case cJSON_Object:
        {
1198 1199
            cJSON *from_child = NULL;
            cJSON *to_child = NULL;
1200 1201
            sort_object(from, case_sensitive);
            sort_object(to, case_sensitive);
1202

1203 1204
            from_child = from->child;
            to_child = to->child;
1205
            /* for all object values in the object with more of them */
1206
            while ((from_child != NULL) || (to_child != NULL))
1207
            {
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
                int diff;
                if (from_child == NULL)
                {
                    diff = 1;
                }
                else if (to_child == NULL)
                {
                    diff = -1;
                }
                else
                {
1219
                    diff = compare_strings((unsigned char*)from_child->string, (unsigned char*)to_child->string, case_sensitive);
1220 1221 1222
                }

                if (diff == 0)
1223 1224
                {
                    /* both object keys are the same */
1225
                    size_t path_length = strlen((const char*)path);
1226
                    size_t from_child_name_length = pointer_encoded_length((unsigned char*)from_child->string);
1227 1228 1229
                    unsigned char *new_path = (unsigned char*)cJSON_malloc(path_length + from_child_name_length + sizeof("/"));

                    sprintf((char*)new_path, "%s/", path);
1230
                    encode_string_as_pointer(new_path + path_length + 1, (unsigned char*)from_child->string);
1231

1232
                    /* create a patch for the element */
1233
                    create_patches(patches, new_path, from_child, to_child, case_sensitive);
C
crhackos 已提交
1234
                    cJSON_free(new_path);
1235 1236 1237

                    from_child = from_child->next;
                    to_child = to_child->next;
1238 1239 1240 1241
                }
                else if (diff < 0)
                {
                    /* object element doesn't exist in 'to' --> remove it */
1242
                    compose_patch(patches, (const unsigned char*)"remove", path, (unsigned char*)from_child->string, NULL);
1243 1244

                    from_child = from_child->next;
1245 1246 1247 1248
                }
                else
                {
                    /* object element doesn't exist in 'from' --> add it */
1249
                    compose_patch(patches, (const unsigned char*)"add", path, (unsigned char*)to_child->string, to_child);
1250 1251

                    to_child = to_child->next;
1252 1253 1254 1255 1256 1257 1258 1259 1260
                }
            }
            return;
        }

        default:
            break;
    }
}
1261

1262
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to)
1263
{
1264 1265 1266 1267 1268 1269 1270 1271
    cJSON *patches = NULL;

    if ((from == NULL) || (to == NULL))
    {
        return NULL;
    }

    patches = cJSON_CreateArray();
1272
    create_patches(patches, (const unsigned char*)"", from, to, false);
1273

1274 1275
    return patches;
}
1276

1277 1278
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to)
{
1279 1280 1281 1282 1283 1284 1285 1286
    cJSON *patches = NULL;

    if ((from == NULL) || (to == NULL))
    {
        return NULL;
    }

    patches = cJSON_CreateArray();
1287 1288 1289 1290 1291
    create_patches(patches, (const unsigned char*)"", from, to, true);

    return patches;
}

1292
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object)
1293
{
1294
    sort_object(object, false);
1295 1296
}

1297
CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object)
M
Max Bruckner 已提交
1298
{
1299
    sort_object(object, true);
M
Max Bruckner 已提交
1300
}
1301

1302
static cJSON *merge_patch(cJSON *target, const cJSON * const patch, const cJSON_bool case_sensitive)
1303
{
M
Max Bruckner 已提交
1304 1305
    cJSON *patch_child = NULL;

1306
    if (!cJSON_IsObject(patch))
M
Max Bruckner 已提交
1307 1308 1309 1310 1311
    {
        /* scalar value, array or NULL, just duplicate */
        cJSON_Delete(target);
        return cJSON_Duplicate(patch, 1);
    }
1312

1313
    if (!cJSON_IsObject(target))
M
Max Bruckner 已提交
1314 1315 1316 1317 1318
    {
        cJSON_Delete(target);
        target = cJSON_CreateObject();
    }

M
Max Bruckner 已提交
1319 1320
    patch_child = patch->child;
    while (patch_child != NULL)
M
Max Bruckner 已提交
1321
    {
M
Max Bruckner 已提交
1322
        if (cJSON_IsNull(patch_child))
M
Max Bruckner 已提交
1323 1324
        {
            /* NULL is the indicator to remove a value, see RFC7396 */
1325 1326 1327 1328 1329 1330 1331 1332
            if (case_sensitive)
            {
                cJSON_DeleteItemFromObjectCaseSensitive(target, patch_child->string);
            }
            else
            {
                cJSON_DeleteItemFromObject(target, patch_child->string);
            }
M
Max Bruckner 已提交
1333 1334 1335
        }
        else
        {
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
            cJSON *replace_me = NULL;
            cJSON *replacement = NULL;

            if (case_sensitive)
            {
                replace_me = cJSON_DetachItemFromObjectCaseSensitive(target, patch_child->string);
            }
            else
            {
                replace_me = cJSON_DetachItemFromObject(target, patch_child->string);
            }

            replacement = merge_patch(replace_me, patch_child, case_sensitive);
            if (replacement == NULL)
            {
                return NULL;
            }

            cJSON_AddItemToObject(target, patch_child->string, replacement);
M
Max Bruckner 已提交
1355
        }
M
Max Bruckner 已提交
1356
        patch_child = patch_child->next;
M
Max Bruckner 已提交
1357 1358
    }
    return target;
1359
}
1360

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch)
{
    return merge_patch(target, patch, false);
}

CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch)
{
    return merge_patch(target, patch, true);
}

1371
static cJSON *generate_merge_patch(cJSON * const from, cJSON * const to, const cJSON_bool case_sensitive)
1372
{
1373 1374
    cJSON *from_child = NULL;
    cJSON *to_child = NULL;
1375
    cJSON *patch = NULL;
1376
    if (to == NULL)
1377 1378 1379 1380
    {
        /* patch to delete everything */
        return cJSON_CreateNull();
    }
1381
    if (!cJSON_IsObject(to) || !cJSON_IsObject(from))
1382 1383 1384 1385
    {
        return cJSON_Duplicate(to, 1);
    }

1386 1387
    sort_object(from, case_sensitive);
    sort_object(to, case_sensitive);
1388

1389 1390
    from_child = from->child;
    to_child = to->child;
1391
    patch = cJSON_CreateObject();
1392
    while (from_child || to_child)
1393
    {
1394 1395 1396 1397 1398
        int diff;
        if (from_child != NULL)
        {
            if (to_child != NULL)
            {
M
Max Bruckner 已提交
1399
                diff = strcmp(from_child->string, to_child->string);
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
            }
            else
            {
                diff = -1;
            }
        }
        else
        {
            diff = 1;
        }

        if (diff < 0)
1412 1413
        {
            /* from has a value that to doesn't have -> remove */
1414 1415 1416
            cJSON_AddItemToObject(patch, from_child->string, cJSON_CreateNull());

            from_child = from_child->next;
1417
        }
1418
        else if (diff > 0)
1419 1420
        {
            /* to has a value that from doesn't have -> add to patch */
1421 1422 1423
            cJSON_AddItemToObject(patch, to_child->string, cJSON_Duplicate(to_child, 1));

            to_child = to_child->next;
1424 1425 1426 1427
        }
        else
        {
            /* object key exists in both objects */
1428
            if (!compare_json(from_child, to_child, case_sensitive))
1429 1430
            {
                /* not identical --> generate a patch */
1431
                cJSON_AddItemToObject(patch, to_child->string, cJSONUtils_GenerateMergePatch(from_child, to_child));
1432
            }
1433

1434
            /* next key in the object */
1435 1436
            from_child = from_child->next;
            to_child = to_child->next;
1437 1438
        }
    }
1439
    if (patch->child == NULL)
1440
    {
1441
        /* no patch generated */
1442
        cJSON_Delete(patch);
1443
        return NULL;
1444 1445 1446
    }

    return patch;
M
Max Bruckner 已提交
1447
}
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457

CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to)
{
    return generate_merge_patch(from, to, false);
}

CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to)
{
    return generate_merge_patch(from, to, true);
}