user_buffer_unpack.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <msgpack.h>
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #define UNPACKED_BUFFER_SIZE 2048
  5. void prepare(msgpack_sbuffer* sbuf) {
  6. msgpack_packer pk;
  7. msgpack_packer_init(&pk, sbuf, msgpack_sbuffer_write);
  8. /* 1st object */
  9. msgpack_pack_array(&pk, 3);
  10. msgpack_pack_int(&pk, 1);
  11. msgpack_pack_true(&pk);
  12. msgpack_pack_str(&pk, 7);
  13. msgpack_pack_str_body(&pk, "example", 7);
  14. /* 2nd object */
  15. msgpack_pack_str(&pk, 6);
  16. msgpack_pack_str_body(&pk, "second", 6);
  17. /* 3rd object */
  18. msgpack_pack_array(&pk, 2);
  19. msgpack_pack_int(&pk, 42);
  20. msgpack_pack_false(&pk);
  21. }
  22. void unpack(char const* buf, size_t len) {
  23. /* buf is allocated by client. */
  24. msgpack_unpacked result;
  25. size_t off = 0;
  26. msgpack_unpack_return ret;
  27. int i = 0;
  28. char unpacked_buffer[UNPACKED_BUFFER_SIZE];
  29. msgpack_unpacked_init(&result);
  30. ret = msgpack_unpack_next(&result, buf, len, &off);
  31. while (ret == MSGPACK_UNPACK_SUCCESS) {
  32. msgpack_object obj = result.data;
  33. /* Use obj. */
  34. printf("Object no %d:\n", ++i);
  35. msgpack_object_print(stdout, obj);
  36. printf("\n");
  37. msgpack_object_print_buffer(unpacked_buffer, UNPACKED_BUFFER_SIZE, obj);
  38. printf("%s\n", unpacked_buffer);
  39. /* If you want to allocate something on the zone, you can use zone. */
  40. /* msgpack_zone* zone = result.zone; */
  41. /* The lifetime of the obj and the zone, */
  42. ret = msgpack_unpack_next(&result, buf, len, &off);
  43. }
  44. msgpack_unpacked_destroy(&result);
  45. if (ret == MSGPACK_UNPACK_CONTINUE) {
  46. printf("All msgpack_object in the buffer is consumed.\n");
  47. }
  48. else if (ret == MSGPACK_UNPACK_PARSE_ERROR) {
  49. printf("The data in the buf is invalid format.\n");
  50. }
  51. }
  52. int main(void) {
  53. msgpack_sbuffer sbuf;
  54. msgpack_sbuffer_init(&sbuf);
  55. prepare(&sbuf);
  56. unpack(sbuf.data, sbuf.size);
  57. msgpack_sbuffer_destroy(&sbuf);
  58. return 0;
  59. }
  60. /* Output */
  61. /*
  62. Object no 1:
  63. [1, true, "example"]
  64. Object no 2:
  65. "second"
  66. Object no 3:
  67. [42, false]
  68. All msgpack_object in the buffer is consumed.
  69. */