serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
8.81k stars 747 forks source link

Explicit enum discriminants (variant_index) are not supported #2763

Open ikhomyakov opened 1 week ago

ikhomyakov commented 1 week ago

As described in the Rust reference, enum discriminant values (a.k.a. variant_indexes) can be assigned explicitly. For example:

#[repr(u8)]
#[derive(Serialize, Deserialize)]
enum Enum {
    Unit = 10,
    Tuple(u16) = 11,
    Struct {
        a: u8,
        b: u16,
    } = 12,
}

The problem is that these values do not get passed down to the serialization methods. For example, if we serialize Enum::Struct { a: 1, b: 2 }, it invokes serialize_struct_variant(self, name = "Enum", variant_index = 2, variant = "Struct", len = 2), whereas it would be reasonable to expect the true enum discriminant variant_index = 12.

Since changing this behavior would introduce a breaking change, it would be helpful to have a container-level attribute (e.g., #[serde(explicit_tags)]) that supports to the true discriminant values. Additionally, if you know of any current workarounds, we would appreciate it.