#enums #parser

macro repr-with-fallback

Automatically generate From and Into impls for enums with custom discriminant values and a fallback variant. Useful for parsing when you might encounter unknown variants and want to hold on to their value.

2 releases

0.1.1 Sep 17, 2022
0.1.0 Sep 17, 2022

#158 in #parsing


Used in 2 crates (via toluol-proto)

MIT license

11KB
157 lines

repr-with-fallback

Automatically generate From and Into impls for enums with custom discriminant values and a fallback variant.

Usage

use repr_with_fallback::repr_with_fallback;

repr_with_fallback! {
    /// A DNSSEC algorithm.
    #[derive(Debug, PartialEq)]
    pub enum Algorithm {
        /// ...
        RSASHA256 = 8,
        RSASHA512 = 10,
        ECDSAP256SHA256 = 13,
        ECDSAP384SHA384 = 14,
        ED25519 = 15,
        Unassigned(u8),
    }
}

assert_eq!(u8::from(Algorithm::ED25519), 15);
assert_eq!(Algorithm::from(15), Algorithm::ED25519);

assert_eq!(u8::from(Algorithm::Unassigned(17)), 17);
assert_eq!(Algorithm::from(17), Algorithm::Unassigned(17));

There are two restrictions imposed on the enum:

  1. It must have only unit variants, except for exactly one variant with exactly one unnamed field. This is used as the fallback variant, and the type of its field must match the type of the discriminants.
  2. Every variant must have a discriminant value provided.

The repr type does not need to be numerical:

repr_with_fallback! {
    pub enum Strings {
        Foo = "static",
        Bar = "string",
        Baz = "slices",
        Spam = "work",
        Eggs = "too",
        Unknown(&'static str),
    }
}

let s: &'static str = Strings::Foo.into();
assert_eq!(s, "static");

Dependencies

~1.5MB
~36K SLoC