Skip to content

Conversation

darkwater
Copy link

Closes #2763.

  • Serialization
  • Deserialization
  • Externally tagged
  • Any other tagging methods (do all apply? I don't think postcard supports all)
  • Proper error handling
  • Tests

Does this approach look good? I'm not great with proc macros and this is my first time contributing to serde.

This makes the following work:

use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[repr(i8)]
#[serde(explicit_tags)]
pub enum Foo {
    Zero,
    One,
    Five = 5,
    Six,
    Ten(u32) = 10,
    Twenty { value: u32 } = 20,
    // Invalid = -1,
    // error:    ^^ unsupported expression for enum discriminant (Serialize)
    //
    // Deserialize panics with "message: unsupported discriminant expression"
}

#[cfg(test)]
mod tests {
    use super::*;

    fn t(value: Foo, expected: &[u8]) {
        let serialized = postcard::to_allocvec(&value).unwrap();
        assert_eq!(serialized, expected);

        let deserialized = postcard::from_bytes::<Foo>(&serialized);
        assert_eq!(deserialized, Ok(value));
    }

    #[test]
    fn test_name() {
        t(Foo::Zero, &[0]);
        t(Foo::One, &[1]);
        t(Foo::Five, &[5]);
        t(Foo::Six, &[6]);
        t(Foo::Ten(42), &[10, 42]);
        t(Foo::Twenty { value: 84 }, &[20, 84]);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Explicit enum discriminants (variant_index) are not supported

1 participant