You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

testReplaceExisting.c 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #ifdef NDEBUG
  2. #undef NDEBUG
  3. #endif
  4. #include <stddef.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include "json.h"
  9. int main(int argc, char **argv)
  10. {
  11. MC_SET_DEBUG(1);
  12. /*
  13. * Check that replacing an existing object keeps the key valid,
  14. * and that it keeps the order the same.
  15. */
  16. json_object *my_object = json_object_new_object();
  17. json_object_object_add(my_object, "foo1", json_object_new_string("bar1"));
  18. json_object_object_add(my_object, "foo2", json_object_new_string("bar2"));
  19. json_object_object_add(my_object, "deleteme", json_object_new_string("bar2"));
  20. json_object_object_add(my_object, "foo3", json_object_new_string("bar3"));
  21. printf("==== delete-in-loop test starting ====\n");
  22. int orig_count = 0;
  23. json_object_object_foreach(my_object, key0, val0)
  24. {
  25. printf("Key at index %d is [%s] %d", orig_count, key0, (val0 == NULL));
  26. if (strcmp(key0, "deleteme") == 0)
  27. {
  28. json_object_object_del(my_object, key0);
  29. printf(" (deleted)\n");
  30. }
  31. else
  32. printf(" (kept)\n");
  33. orig_count++;
  34. }
  35. printf("==== replace-value first loop starting ====\n");
  36. const char *original_key = NULL;
  37. orig_count = 0;
  38. json_object_object_foreach(my_object, key, val)
  39. {
  40. printf("Key at index %d is [%s] %d\n", orig_count, key, (val == NULL));
  41. orig_count++;
  42. if (strcmp(key, "foo2") != 0)
  43. continue;
  44. printf("replacing value for key [%s]\n", key);
  45. original_key = key;
  46. json_object_object_add(my_object, key, json_object_new_string("zzz"));
  47. }
  48. printf("==== second loop starting ====\n");
  49. int new_count = 0;
  50. int retval = 0;
  51. json_object_object_foreach(my_object, key2, val2)
  52. {
  53. printf("Key at index %d is [%s] %d\n", new_count, key2, (val2 == NULL));
  54. new_count++;
  55. if (strcmp(key2, "foo2") != 0)
  56. continue;
  57. printf("pointer for key [%s] does %smatch\n", key2,
  58. (key2 == original_key) ? "" : "NOT ");
  59. if (key2 != original_key)
  60. retval = 1;
  61. }
  62. if (new_count != orig_count)
  63. {
  64. printf("mismatch between original count (%d) and new count (%d)\n", orig_count,
  65. new_count);
  66. retval = 1;
  67. }
  68. json_object_put(my_object);
  69. return retval;
  70. }