3 releases

0.1.3 Sep 18, 2023
0.1.2 Sep 18, 2023
0.1.1 Sep 18, 2023

#15 in #discriminant

Download history 43/week @ 2024-07-04 59/week @ 2024-07-11 76/week @ 2024-07-18 79/week @ 2024-07-25 189/week @ 2024-08-01 175/week @ 2024-08-08 101/week @ 2024-08-15 127/week @ 2024-08-22 128/week @ 2024-08-29 72/week @ 2024-09-05 47/week @ 2024-09-12 79/week @ 2024-09-19 118/week @ 2024-09-26 149/week @ 2024-10-03 139/week @ 2024-10-10 244/week @ 2024-10-17

663 downloads per month
Used in 4 crates (via smb3)

MIT license

16KB
323 lines

serde_dis

This crate provides two macros for generating a serde Serialize and Deserialize implementation for enums.

These are SerializeWithDiscriminant and DeserializeWithDiscriminant

The implementations serializes and deserializes an enum as a struct with the discriminant as the first field and the variant fields as the following fields.

The Deserialize implementation expects the deserializer to call visit_seq for structs, this is mainly because the deserializers I was targeting do things this way. visit_map could be implemented but there is a caveat here which is that this strategy would only work if the map being deserialized always has the discriminant as the first entry.

Here are some examples

This enum will be serialized / deserialized as a u32

  #[derive(DeserializeWithDiscriminant, SerializeWithDiscriminant, Debug, PartialEq)]
  #[repr(u32)]
  enum Foo {
      A = 1,
      B = 2,
      C = 3,
  }

It also supports enums with fields

This enum will first serialize / deserialize its discriminant value (a u16) then any fields

  #[derive(DeserializeWithDiscriminant, SerializeWithDiscriminant, Debug, PartialEq)]
  #[repr(u16)]
  enum Bar {
      A(String) = 1,
      B {
          a: i32,
          b: u32,
      } = 12,
      C(i32, u64) = 7,
      #[serde(other)]
      D = 9,
  }

supported serde attributes

  • other this makes it so any unknown discriminant deserializes as this given variant
  • rename the container attribute. This lets you rename the enum.

Dependencies

~245–690KB
~16K SLoC