repr-with-fallback

Crates.iorepr-with-fallback
lib.rsrepr-with-fallback
version0.1.1
sourcesrc
created_at2022-09-17 11:39:24.829533
updated_at2022-09-17 11:42:51.414976
descriptionAutomatically 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.
homepage
repositoryhttps://sr.ht/~mvforell/repr-with-fallback
max_upload_size
id668136
size11,441
Max von Forell (mvforell)

documentation

https://docs.rs/repr-with-fallback

README

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");
Commit count: 0

cargo fmt