pyfisch / cbor

CBOR support for serde.
https://docs.rs/serde_cbor/
Apache License 2.0
297 stars 99 forks source link

Serialize structs as array #107

Open dereulenspiegel opened 5 years ago

dereulenspiegel commented 5 years ago

For some use cases it would be very useful to be able to serialize structs as CBOR arrays. The CDDL (https://datatracker.ietf.org/doc/draft-ietf-cbor-cddl/?include_text=1) actually specifies that this should be possible with CBOR and implementations in other languages support this too. On my current project I am trying to implement a representation of certificates with CBOR (https://tools.ietf.org/id/draft-raza-ace-cbor-certificates-00.html) and this requires the struct to be represented as array (which is also even more concise as the current packed format).

Would it make sense to support this in this library or is the more idiomatic way to implement a custom Serializer/Deserializer? In my humble opinion it would be great to have an attribute on structs to control this.

pyfisch commented 5 years ago

Hi,

for now it is easiest to implement it as a custom Serializer/Deserializer. But the more idiomatic way would be to create a new container attribute in serde that specifies that this struct should be serialized as an array.

ghost commented 5 years ago

The deserializer part of this is already implemented by accident. The correct way to implement it would be to adapt Serde Derive to have a container attribute for this purpose.

petreeftime commented 5 years ago

I have solved a similar issue by defining the structs as tuples instead, although it's not the nicest way to do this. eg:

struct A { } // serializes as map
struct A ( ) // serializes as array