test_dump_callback.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2009-2016 Petri Lehtinen <[email protected]>
  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 "util.h"
  8. #include <jansson.h>
  9. #include <stdlib.h>
  10. #include <string.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. struct my_sink s;
  27. json_t *json;
  28. const char str[] = "[\"A\", {\"B\": \"C\", \"e\": false}, 1, null, \"foo\"]";
  29. char *dumped_to_string;
  30. json = json_loads(str, 0, NULL);
  31. if (!json) {
  32. fail("json_loads failed");
  33. }
  34. dumped_to_string = json_dumps(json, 0);
  35. if (!dumped_to_string) {
  36. json_decref(json);
  37. fail("json_dumps failed");
  38. }
  39. s.off = 0;
  40. s.cap = strlen(dumped_to_string);
  41. s.buf = malloc(s.cap);
  42. if (!s.buf) {
  43. json_decref(json);
  44. free(dumped_to_string);
  45. fail("malloc failed");
  46. }
  47. if (json_dump_callback(json, my_writer, &s, 0) == -1) {
  48. json_decref(json);
  49. free(dumped_to_string);
  50. free(s.buf);
  51. fail("json_dump_callback failed on an exact-length sink buffer");
  52. }
  53. if (strncmp(dumped_to_string, s.buf, s.off) != 0) {
  54. json_decref(json);
  55. free(dumped_to_string);
  56. free(s.buf);
  57. fail("json_dump_callback and json_dumps did not produce identical "
  58. "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 "
  66. "have failed");
  67. }
  68. json_decref(json);
  69. free(dumped_to_string);
  70. free(s.buf);
  71. }