xref: /freebsd/contrib/libcbor/examples/create_items.c (revision 188bf8876fdc6e3edebeb76f80e764e419a65f1e)
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(void) {
12   /* Preallocate the map structure */
13   cbor_item_t* root = cbor_new_definite_map(2);
14   /* Add the content */
15   bool success = cbor_map_add(
16       root, (struct cbor_pair){
17                 .key = cbor_move(cbor_build_string("Is CBOR awesome?")),
18                 .value = cbor_move(cbor_build_bool(true))});
19   success &= cbor_map_add(
20       root, (struct cbor_pair){
21                 .key = cbor_move(cbor_build_uint8(42)),
22                 .value = cbor_move(cbor_build_string("Is the answer"))});
23   if (!success) return 1;
24   /* Output: `length` bytes of data in the `buffer` */
25   unsigned char* buffer;
26   size_t buffer_size;
27   cbor_serialize_alloc(root, &buffer, &buffer_size);
28 
29   fwrite(buffer, 1, buffer_size, stdout);
30   free(buffer);
31 
32   fflush(stdout);
33   cbor_decref(&root);
34 }
35