test_dump_callback.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
  3. *
  4. * Jansson is free software; you can redistribute it and/or modify
  5. * it under the terms of the MIT license. See LICENSE for details.
  6. */
  7. #include <jansson.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #include "util.h"
  11. struct my_sink {
  12. char *buf;
  13. size_t off;
  14. size_t cap;
  15. };
  16. static int my_writer(const char *buffer, size_t len, void *data) {
  17. struct my_sink *s = data;
  18. if (len > s->cap - s->off) {
  19. return -1;
  20. }
  21. memcpy(s->buf + s->off, buffer, len);
  22. s->off += len;
  23. return 0;
  24. }
  25. static void run_tests()
  26. {
  27. struct my_sink s;
  28. json_t *json;
  29. const char str[] = "[\"A\", {\"B\": \"C\", \"e\": false}, 1, null, \"foo\"]";
  30. char *dumped_to_string;
  31. json = json_loads(str, 0, NULL);
  32. if(!json) {
  33. fail("json_loads failed");
  34. }
  35. dumped_to_string = json_dumps(json, 0);
  36. if (!dumped_to_string) {
  37. json_decref(json);
  38. fail("json_dumps failed");
  39. }
  40. s.off = 0;
  41. s.cap = strlen(dumped_to_string);
  42. s.buf = malloc(s.cap);
  43. if (!s.buf) {
  44. json_decref(json);
  45. free(dumped_to_string);
  46. fail("malloc failed");
  47. }
  48. if (json_dump_callback(json, my_writer, &s, 0) == -1) {
  49. json_decref(json);
  50. free(dumped_to_string);
  51. free(s.buf);
  52. fail("json_dump_callback failed on an exact-length sink buffer");
  53. }
  54. if (strncmp(dumped_to_string, s.buf, s.off) != 0) {
  55. json_decref(json);
  56. free(dumped_to_string);
  57. free(s.buf);
  58. fail("json_dump_callback and json_dumps did not produce identical output");
  59. }
  60. s.off = 1;
  61. if (json_dump_callback(json, my_writer, &s, 0) != -1) {
  62. json_decref(json);
  63. free(dumped_to_string);
  64. free(s.buf);
  65. fail("json_dump_callback succeeded on a short buffer when it should have failed");
  66. }
  67. json_decref(json);
  68. free(dumped_to_string);
  69. free(s.buf);
  70. }