NordicSemiconductor / zcbor

Low footprint C/C++ CBOR library and Python tool providing code generation from CDDL descriptions.
Apache License 2.0
105 stars 34 forks source link

Possible to get away from indefinite length arrays by encoding optionals first? #417

Open jnz86 opened 2 months ago

jnz86 commented 2 months ago

I have a map object with a couple optional byte strings. Now, my encoded object is always of indefinite length.

I suspect this is because the streaming encoder needs to make a decision at the creation of the map, and it simple hasn't checked to see if xxx_present yet.

Would it be possible that on cbor_encode_xxx() that optionals were checked for presence first, then the encoder would have a solid idea of the number of values that will be encoded and use that vs indefinite length?

oyvindronningstad commented 2 months ago

If you enable ZCBOR_CANONICAL you get definite length arrays no matter what. zcbor goes back to the header and writes the length when calling zcbor_list_encode_end(). What you suggest is definitely possible, but I don't know if it's useful, since it means you need more code, and it only works for certain structures. It could work for all structures if you take into account all repeats and optionals, but the complexity needed in the generation code will be substantial. I'll think more about this, thanks for the suggestion.