cbor
cbor copied to clipboard
how to make sure a Vec<u8> is serialized as `bytes`?
I have a structure with a Vec<u8> that I serialize from Rust, using cbor::ser::to_writer_packed
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LevelInfo {
pub name: String,
pub intro: Vec<Span>,
pub code: Vec<u8>,
}
in Python, the code field deserializes to something like
2: [127,
69,
76,
70,
1,
1,
1,
0,
What I would expect is b'\x7fELF\x01\0x01\0x01\0x00'. It looks that it is using an array of individual values instead.
This is using a lot of extra space, is it possible to avoid this and use cbor's native bytes type?
(sorry if this is a stupid question, could not find anything about annotations!)
You can use the serde_bytes crate.
awesome, thank you! basically just
#[serde(with = "serde_bytes")]
pub code: Vec<u8>,
and it worked it is embedded verbatim now
Maybe information about serde_bytes should be more visible in main serde_cbor's README and root doccomment?
Yes I agree it would be good to mention this interaction with serde_bytes, though looking through the manual I'm not sure where it would fit in. Maybe a section that specifies how rust types are mapped to CBOR types and vice versa would be useful, and could mention this.
If I migrate to serde_bytes is there any way to keep CBOR compatible with older versions of the document that didn't use byte strings, currently they are incompatible (I can an error that the deserializer expected a byte string)
@jawline You will need to write a custom deserializer that accepts either byte arrays or byte strings.
It seems I misunderstood my issue a little bit, serde bytes is actually compatible with the old encoded data for cbor but older clients are now incompatible with data produced serde bytes > cbor for Vec