jamesmunns / postcard

A no_std + serde compatible message library for Rust
Apache License 2.0
943 stars 91 forks source link

How to explicitly specify field order ? #94

Closed luqasz closed 1 year ago

luqasz commented 1 year ago

Hi.

I am new to serde and postcard. I haven't seen any way of stating in which order should fields be serialized. Is it possible ?

jamesmunns commented 1 year ago

Hi @luqasz, this is talked about a bit in the postcard spec, but generally: fields get serialized in the order they are defined in Rust, including nested fields.

For example:

struct One {
    a: u32,
    b: u8,
    c: Two,
    f: bool,
}

struct Two {
    d: i8,
    e: i16,
}

Would look like this on the wire:

|--------- One ---------|
          |-- Two -|

[ a ][ b ][ d ][ e ][ f ]
  |    |    |    |    \-> One::f
  |    |    |    \-> One::c::e
  |    |    \-> One::c::d
  |    \-> One::b
  \-> One::a

There isn't a way to reorder these, other than changing the definition of the struct you are serializing.

luqasz commented 1 year ago

ok. Thx. I will write same in c++ as I am writing embedded code in c++ and app in rust. Good that rust reorders fields in struct to maintain alignment under the hood.