1245383Sjilles#include <msgpack.h> 2245383Sjilles#include <stdio.h> 3245383Sjilles#include <assert.h> 4245383Sjilles 5245383Sjillesvoid prepare(msgpack_sbuffer* sbuf) { 6245383Sjilles msgpack_packer pk; 7245383Sjilles 8245383Sjilles msgpack_packer_init(&pk, sbuf, msgpack_sbuffer_write); 9245383Sjilles /* 1st object */ 10245383Sjilles msgpack_pack_array(&pk, 3); 11 msgpack_pack_int(&pk, 1); 12 msgpack_pack_true(&pk); 13 msgpack_pack_str(&pk, 7); 14 msgpack_pack_str_body(&pk, "example", 7); 15 /* 2nd object */ 16 msgpack_pack_str(&pk, 6); 17 msgpack_pack_str_body(&pk, "second", 6); 18 /* 3rd object */ 19 msgpack_pack_array(&pk, 2); 20 msgpack_pack_int(&pk, 42); 21 msgpack_pack_false(&pk); 22} 23 24void unpack(char const* buf, size_t len) { 25 /* buf is allocated by client. */ 26 msgpack_unpacked result; 27 size_t off = 0; 28 msgpack_unpack_return ret; 29 int i = 0; 30 msgpack_unpacked_init(&result); 31 ret = msgpack_unpack_next(&result, buf, len, &off); 32 while (ret == MSGPACK_UNPACK_SUCCESS) { 33 msgpack_object obj = result.data; 34 35 /* Use obj. */ 36 printf("Object no %d:\n", ++i); 37 msgpack_object_print(stdout, obj); 38 printf("\n"); 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 43 ret = msgpack_unpack_next(&result, buf, len, &off); 44 } 45 msgpack_unpacked_destroy(&result); 46 47 if (ret == MSGPACK_UNPACK_CONTINUE) { 48 printf("All msgpack_object in the buffer is consumed.\n"); 49 } 50 else if (ret == MSGPACK_UNPACK_PARSE_ERROR) { 51 printf("The data in the buf is invalid format.\n"); 52 } 53} 54 55int main(void) { 56 msgpack_sbuffer sbuf; 57 msgpack_sbuffer_init(&sbuf); 58 59 prepare(&sbuf); 60 unpack(sbuf.data, sbuf.size); 61 62 msgpack_sbuffer_destroy(&sbuf); 63 return 0; 64} 65 66/* Output */ 67 68/* 69Object no 1: 70[1, true, "example"] 71Object no 2: 72"second" 73Object no 3: 74[42, false] 75All msgpack_object in the buffer is consumed. 76*/ 77