xref: /freebsd/contrib/libcbor/examples/create_items.c (revision 3e8eb5c7f4909209c042403ddee340b2ee7003a5)
1 /*
2  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3  *
4  * libcbor 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 
8 #include <stdio.h>
9 #include "cbor.h"
10 
11 int main(int argc, char* argv[]) {
12   /* Preallocate the map structure */
13   cbor_item_t* root = cbor_new_definite_map(2);
14   /* Add the content */
15   cbor_map_add(root,
16                (struct cbor_pair){
17                    .key = cbor_move(cbor_build_string("Is CBOR awesome?")),
18                    .value = cbor_move(cbor_build_bool(true))});
19   cbor_map_add(root,
20                (struct cbor_pair){
21                    .key = cbor_move(cbor_build_uint8(42)),
22                    .value = cbor_move(cbor_build_string("Is the answer"))});
23   /* Output: `length` bytes of data in the `buffer` */
24   unsigned char* buffer;
25   size_t buffer_size,
26       length = cbor_serialize_alloc(root, &buffer, &buffer_size);
27 
28   fwrite(buffer, 1, length, stdout);
29   free(buffer);
30 
31   fflush(stdout);
32   cbor_decref(&root);
33 }
34