Future-proofing message serialization

Following up on How do I future proof (de)serialization of types that might change across versions? - #2 by Schard , the accepted answer is to use versioned enums like

#[derive(Serialize, Deserialize)]
enum MyThing {
  V1(pub MyThingV1),
  V2(pub MyThingV2),
  ...
}

While I am in love with this approach, enum discriminants aren’t stable if you change the definition or the Rust compiler. Reading the language section Enumerations - The Rust Reference , I’m led to believe that if the following does explicitly constrain the discriminant so we don’t have this issue as long as I only ever append to the enum list:

#[repr(u32)]
#[derive(Serialize, Deserialize)]
enum MyThing {
  First = 0
  V1(pub MyThingV1),
  V2(pub MyThingV2),
  ...
}

I suppose there’s also a second possibility that serde doesn’t case about discriminants and assigns its own for enum variants for serialization purposes.

Unless you’re using something like serde_repr, the enum discriminants do not play any role in de-/serialization.

Also, you can add discriminants to enums with associated data, if needed.

#[derive(Serialize, Deserialize)]
#[repr(u8)]
enum MyThing {
  V1(pub MyThingV1) = 0x01,
  V2(pub MyThingV2) = 0x02,
  ...
}

If the versions are expected to change more or less frequently, you’d also want to declare them #[non_exhaustive]:

#[derive(Serialize, Deserialize)]
#[non_exhaustive]
#[repr(u8)]
enum MyThing {
  V1(pub MyThingV1) = 0x01,
  V2(pub MyThingV2) = 0x02,
  ...
}
1 Like

You're mixing things here. The discriminants for the in-memory representation are not the same discriminants for the (de)serialization. On top of that, with serde you can choose which field to use for the discriminant:

derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum Message {
    Request { id: String, method: String, params: Params },
    Response { id: String, result: Value },
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.