1Decoding 2============================= 3 4Another way to decode data using libcbor is to specify a callbacks that will be invoked when upon finding certain items in the input. This service is provided by 5 6.. doxygenfunction:: cbor_stream_decode 7 8 9To get started, you might want to have a look at the simple streaming example: 10 11.. code-block:: c 12 13 #include "cbor.h" 14 #include <stdio.h> 15 #include <string.h> 16 17 /* 18 * Illustrates how one might skim through a map (which is assumed to have 19 * string keys and values only), looking for the value of a specific key 20 * 21 * Use the examples/data/map.cbor input to test this. 22 */ 23 24 const char * key = "a secret key"; 25 bool key_found = false; 26 27 void find_string(void * _ctx, cbor_data buffer, size_t len) 28 { 29 if (key_found) { 30 printf("Found the value: %*s\n", (int) len, buffer); 31 key_found = false; 32 } else if (len == strlen(key)) { 33 key_found = (memcmp(key, buffer, len) == 0); 34 } 35 } 36 37 int main(int argc, char * argv[]) 38 { 39 FILE * f = fopen(argv[1], "rb"); 40 fseek(f, 0, SEEK_END); 41 size_t length = (size_t)ftell(f); 42 fseek(f, 0, SEEK_SET); 43 unsigned char * buffer = malloc(length); 44 fread(buffer, length, 1, f); 45 46 struct cbor_callbacks callbacks = cbor_empty_callbacks; 47 struct cbor_decoder_result decode_result; 48 size_t bytes_read = 0; 49 callbacks.string = find_string; 50 while (bytes_read < length) { 51 decode_result = cbor_stream_decode(buffer + bytes_read, 52 length - bytes_read, 53 &callbacks, NULL); 54 bytes_read += decode_result.read; 55 } 56 57 free(buffer); 58 fclose(f); 59 } 60 61The callbacks are defined by 62 63.. doxygenstruct:: cbor_callbacks 64 :members: 65 66When building custom sets of callbacks, feel free to start from 67 68.. doxygenvariable:: cbor_empty_callbacks 69 70Related structures 71~~~~~~~~~~~~~~~~~~~~~ 72 73.. doxygenenum:: cbor_decoder_status 74.. doxygenstruct:: cbor_decoder_result 75 :members: 76 77 78Callback types definition 79~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 80 81 82.. doxygentypedef:: cbor_int8_callback 83.. doxygentypedef:: cbor_int16_callback 84.. doxygentypedef:: cbor_int32_callback 85.. doxygentypedef:: cbor_int64_callback 86.. doxygentypedef:: cbor_simple_callback 87.. doxygentypedef:: cbor_string_callback 88.. doxygentypedef:: cbor_collection_callback 89.. doxygentypedef:: cbor_float_callback 90.. doxygentypedef:: cbor_double_callback 91.. doxygentypedef:: cbor_bool_callback 92