xref: /freebsd/contrib/libcbor/examples/create_items.c (revision 5d3e7166f6a0187fa3f8831b16a06bd9955c21ff)
110ff414cSEd Maste /*
210ff414cSEd Maste  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
310ff414cSEd Maste  *
410ff414cSEd Maste  * libcbor is free software; you can redistribute it and/or modify
510ff414cSEd Maste  * it under the terms of the MIT license. See LICENSE for details.
610ff414cSEd Maste  */
710ff414cSEd Maste 
810ff414cSEd Maste #include <stdio.h>
910ff414cSEd Maste #include "cbor.h"
1010ff414cSEd Maste 
main(void)11*5d3e7166SEd Maste int main(void) {
1210ff414cSEd Maste   /* Preallocate the map structure */
1310ff414cSEd Maste   cbor_item_t* root = cbor_new_definite_map(2);
1410ff414cSEd Maste   /* Add the content */
15*5d3e7166SEd Maste   bool success = cbor_map_add(
16*5d3e7166SEd Maste       root, (struct cbor_pair){
1710ff414cSEd Maste                 .key = cbor_move(cbor_build_string("Is CBOR awesome?")),
1810ff414cSEd Maste                 .value = cbor_move(cbor_build_bool(true))});
19*5d3e7166SEd Maste   success &= cbor_map_add(
20*5d3e7166SEd Maste       root, (struct cbor_pair){
2110ff414cSEd Maste                 .key = cbor_move(cbor_build_uint8(42)),
2210ff414cSEd Maste                 .value = cbor_move(cbor_build_string("Is the answer"))});
23*5d3e7166SEd Maste   if (!success) return 1;
2410ff414cSEd Maste   /* Output: `length` bytes of data in the `buffer` */
2510ff414cSEd Maste   unsigned char* buffer;
26*5d3e7166SEd Maste   size_t buffer_size;
27*5d3e7166SEd Maste   cbor_serialize_alloc(root, &buffer, &buffer_size);
2810ff414cSEd Maste 
29*5d3e7166SEd Maste   fwrite(buffer, 1, buffer_size, stdout);
3010ff414cSEd Maste   free(buffer);
3110ff414cSEd Maste 
3210ff414cSEd Maste   fflush(stdout);
3310ff414cSEd Maste   cbor_decref(&root);
3410ff414cSEd Maste }
35