intel/tinycbor

Documentation issues

mwo-ext-airmaster opened this issue · 2 comments

Thank you for the library. :)

Would you consider to improve the documentation and include an example which shows how to:
encode an array of for example bool?

Write that using at least one cbor_encoder_create_array() when encoding values is mandatory?
The decoder asserts without it when decoding the input.

How to encode/decode more than one array?

I would love to write a couple of examples, but reading the documentation left my confused.

For instance .. when encoding a bool I discovered that I had to use:
cbor_encode_simple_value() and not cbor_encode_boolean() as the later could not be decoded.

cbor_encode_boolean should work.

#include <cbor.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    int n = strtol(argv[1], nullptr, 0);

    uint8_t buf[n + 9];
    CborEncoder encoder;
    cbor_encoder_init(&encoder, buf, n + 9, 0);

    CborEncoder array;
    cbor_encoder_create_array(&encoder, &array, n);
    for (int i = 0; i < n; ++i)
        cbor_encode_boolean(&array, (i % 4 == 0));
    cbor_encoder_close_container(&encoder, &array);

    n = cbor_encoder_get_buffer_size(&encoder, buf);
    fwrite(buf, 1, n, stdout);
}
$ g++ cborboolarray.cpp -I$OLDPWD/src  -L$OLDPWD/lib -ltinycbor
$ ./a.out 13 | od -tx1               
0000000 8d f5 f4 f4 f4 f5 f4 f4 f4 f5 f4 f4 f4 f5
$ /tmp/a.out 13 | ./cbordump
[
    true,
    false,
    false,
    false,
    true,
    false,
    false,
    false,
    true,
    false,
    false,
    false,
    true
]
`$ /tmp/a.out 13 | ./cbordump -a
8d                                                 # Array length 13
  f5                                               # Simple Type true
  f4                                               # Simple Type false
  f4                                               # Simple Type false
  f4                                               # Simple Type false
  f5                                               # Simple Type true
  f4                                               # Simple Type false
  f4                                               # Simple Type false
  f4                                               # Simple Type false
  f5                                               # Simple Type true
  f4                                               # Simple Type false
  f4                                               # Simple Type false
  f4                                               # Simple Type false
  f5                                               # Simple Type true
``

Error checking is left as an exercise to the reader