xref: /freebsd/contrib/libcbor/doc/source/using.rst (revision 81b22a98)
1Usage & preliminaries
2=======================
3
4Version information
5--------------------
6
7libcbor exports its version using three self-explanatory macros:
8
9 - ``CBOR_MAJOR_VERSION``
10 - ``CBOR_MINOR_VERSION``
11 - ``CBOR_PATCH_VERSION``
12
13The ``CBOR_VERSION`` is a string concatenating these three identifiers into one (e.g. ``0.2.0``).
14
15In order to simplify version comparisons, the version is also exported as
16
17.. code-block:: c
18
19  #define CBOR_HEX_VERSION ((CBOR_MAJOR_VERSION << 16) | (CBOR_MINOR_VERSION << 8) | CBOR_PATCH_VERSION)
20
21Since macros are difficult to work with through FFIs, the same information is also available through three ``uint8_t`` constants,
22namely
23
24 - ``cbor_major_version``
25 - ``cbor_minor_version``
26 - ``cbor_patch_version``
27
28
29Headers to include
30---------------------
31
32The ``cbor.h`` header includes all the symbols. If, for any reason, you don't want to include all the exported symbols,
33feel free to use just some of the ``cbor/*.h`` headers:
34
35 - ``cbor/arrays.h`` - :doc:`api/type_4`
36 - ``cbor/bytestrings.h`` - :doc:`api/type_2`
37 - ``cbor/callbacks.h`` - Callbacks used for :doc:`streaming/decoding`
38 - ``cbor/common.h`` - Common utilities - always transitively included
39 - ``cbor/data.h`` - Data types definitions - always transitively included
40 - ``cbor/encoding.h`` - Streaming encoders for :doc:`streaming/encoding`
41 - ``cbor/floats_ctrls.h`` - :doc:`api/type_7`
42 - ``cbor/ints.h`` - :doc:`api/type_0_1`
43 - ``cbor/maps.h`` - :doc:`api/type_5`
44 - ``cbor/serialization.h`` - High level serialization such as :func:`cbor_serialize`
45 - ``cbor/streaming.h`` - Home of :func:`cbor_stream_decode`
46 - ``cbor/strings.h`` - :doc:`api/type_3`
47 - ``cbor/tags.h`` - :doc:`api/type_6`
48
49
50Using libcbor
51--------------
52
53If you want to get more familiar with CBOR, we recommend the `cbor.io <http://cbor.io/>`_ website. Once you get the grasp
54of what is it CBOR does, the examples (located in the ``examples`` directory) should give you a good feel of the API. The
55:doc:`API documentation <api>` should then provide with all the information you may need.
56
57
58**Creating and serializing items**
59
60.. code-block:: c
61
62    #include "cbor.h"
63    #include <stdio.h>
64
65    int main(int argc, char * argv[])
66    {
67        /* Preallocate the map structure */
68        cbor_item_t * root = cbor_new_definite_map(2);
69        /* Add the content */
70        cbor_map_add(root, (struct cbor_pair) {
71            .key = cbor_move(cbor_build_string("Is CBOR awesome?")),
72            .value = cbor_move(cbor_build_bool(true))
73        });
74        cbor_map_add(root, (struct cbor_pair) {
75            .key = cbor_move(cbor_build_uint8(42)),
76            .value = cbor_move(cbor_build_string("Is the answer"))
77        });
78        /* Output: `length` bytes of data in the `buffer` */
79        unsigned char * buffer;
80        size_t buffer_size, length = cbor_serialize_alloc(root, &buffer, &buffer_size);
81
82        fwrite(buffer, 1, length, stdout);
83        free(buffer);
84
85        fflush(stdout);
86        cbor_decref(&root);
87    }
88
89
90**Reading serialized data**
91
92.. code-block:: c
93
94    #include "cbor.h"
95    #include <stdio.h>
96
97    /*
98     * Reads data from a file. Example usage:
99     * $ ./examples/readfile examples/data/nested_array.cbor
100     */
101
102    int main(int argc, char * argv[])
103    {
104        FILE * f = fopen(argv[1], "rb");
105        fseek(f, 0, SEEK_END);
106        size_t length = (size_t)ftell(f);
107        fseek(f, 0, SEEK_SET);
108        unsigned char * buffer = malloc(length);
109        fread(buffer, length, 1, f);
110
111        /* Assuming `buffer` contains `info.st_size` bytes of input data */
112        struct cbor_load_result result;
113        cbor_item_t * item = cbor_load(buffer, length, &result);
114        /* Pretty-print the result */
115        cbor_describe(item, stdout);
116        fflush(stdout);
117        /* Deallocate the result */
118        cbor_decref(&item);
119
120        fclose(f);
121    }
122
123
124**Using the streaming parser**
125
126.. code-block:: c
127
128    #include "cbor.h"
129    #include <stdio.h>
130    #include <string.h>
131
132    /*
133     * Illustrates how one might skim through a map (which is assumed to have
134     * string keys and values only), looking for the value of a specific key
135     *
136     * Use the examples/data/map.cbor input to test this.
137     */
138
139    const char * key = "a secret key";
140    bool key_found = false;
141
142    void find_string(void * _ctx, cbor_data buffer, size_t len)
143    {
144        if (key_found) {
145            printf("Found the value: %*s\n", (int) len, buffer);
146            key_found = false;
147        } else if (len == strlen(key)) {
148            key_found = (memcmp(key, buffer, len) == 0);
149        }
150    }
151
152    int main(int argc, char * argv[])
153    {
154        FILE * f = fopen(argv[1], "rb");
155        fseek(f, 0, SEEK_END);
156        size_t length = (size_t)ftell(f);
157        fseek(f, 0, SEEK_SET);
158        unsigned char * buffer = malloc(length);
159        fread(buffer, length, 1, f);
160
161        struct cbor_callbacks callbacks = cbor_empty_callbacks;
162        struct cbor_decoder_result decode_result;
163        size_t bytes_read = 0;
164        callbacks.string = find_string;
165        while (bytes_read < length) {
166            decode_result = cbor_stream_decode(buffer + bytes_read,
167                                               length - bytes_read,
168                                               &callbacks, NULL);
169            bytes_read += decode_result.read;
170        }
171
172        fclose(f);
173    }
174