xref: /netbsd-src/external/mit/libcbor/dist/examples/create_items.c (revision 5dd36a3bc8bf2a9dec29ceb6349550414570c447)
1*5dd36a3bSchristos /*
2*5dd36a3bSchristos  * Copyright (c) 2014-2019 Pavel Kalvoda <me@pavelkalvoda.com>
3*5dd36a3bSchristos  *
4*5dd36a3bSchristos  * libcbor is free software; you can redistribute it and/or modify
5*5dd36a3bSchristos  * it under the terms of the MIT license. See LICENSE for details.
6*5dd36a3bSchristos  */
7*5dd36a3bSchristos 
8*5dd36a3bSchristos #include <stdio.h>
9*5dd36a3bSchristos #include "cbor.h"
10*5dd36a3bSchristos 
main(int argc,char * argv[])11*5dd36a3bSchristos int main(int argc, char* argv[]) {
12*5dd36a3bSchristos   /* Preallocate the map structure */
13*5dd36a3bSchristos   cbor_item_t* root = cbor_new_definite_map(2);
14*5dd36a3bSchristos   /* Add the content */
15*5dd36a3bSchristos   cbor_map_add(root,
16*5dd36a3bSchristos                (struct cbor_pair){
17*5dd36a3bSchristos                    .key = cbor_move(cbor_build_string("Is CBOR awesome?")),
18*5dd36a3bSchristos                    .value = cbor_move(cbor_build_bool(true))});
19*5dd36a3bSchristos   cbor_map_add(root,
20*5dd36a3bSchristos                (struct cbor_pair){
21*5dd36a3bSchristos                    .key = cbor_move(cbor_build_uint8(42)),
22*5dd36a3bSchristos                    .value = cbor_move(cbor_build_string("Is the answer"))});
23*5dd36a3bSchristos   /* Output: `length` bytes of data in the `buffer` */
24*5dd36a3bSchristos   unsigned char* buffer;
25*5dd36a3bSchristos   size_t buffer_size,
26*5dd36a3bSchristos       length = cbor_serialize_alloc(root, &buffer, &buffer_size);
27*5dd36a3bSchristos 
28*5dd36a3bSchristos   fwrite(buffer, 1, length, stdout);
29*5dd36a3bSchristos   free(buffer);
30*5dd36a3bSchristos 
31*5dd36a3bSchristos   fflush(stdout);
32*5dd36a3bSchristos   cbor_decref(&root);
33*5dd36a3bSchristos }
34