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

Decoder does not support "default" #412

Open mkschreder opened 4 months ago

mkschreder commented 4 months ago

The ".default" option on cddl fields creates parse error in the cddl parser.

Expected behavior

".default" option should be parsed correctly and then used to set default value for fields that are optional and either not provided in the incoming data or provided and set to "null" (F6) when decoding. If a field is defined as "? my_field: uint .default 1" and the incoming data has this feld set to null then the decoder should assign default value to the field of the target struct.

Up for discussion

The exact behavior is of course open for discussion because I don't see much about this in the spec but this is something that is absolutely essential for smooth operation. You want to be able to communicate the intent to reset a field to default value by simply setting it to null or not supplying it at all. The result should be handled by the decoder automatically.

The spec only mentions this:

image

In practice, however, the use of default is the only straightforward way to implement "put" semantics in the backend without having to specify all fields yet still overwriting field values to defaults in the resulting message. If default is not handled at all, then a lot of custom code needs to be added to check if fields exist and then to set them to reasonable defaults. It would be good to avoid this and to simply make default handling an automatic function of the generated decoder.

oyvindronningstad commented 2 months ago

Thanks for the report. I can see how it would be useful, and hope to implement it soon.