Crates.io | repr-with-fallback |
lib.rs | repr-with-fallback |
version | 0.1.1 |
source | src |
created_at | 2022-09-17 11:39:24.829533 |
updated_at | 2022-09-17 11:42:51.414976 |
description | 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. |
homepage | |
repository | https://sr.ht/~mvforell/repr-with-fallback |
max_upload_size | |
id | 668136 |
size | 11,441 |
repr-with-fallback
Automatically generate From
and Into
impls for enum
s with custom discriminant values
and a fallback variant.
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
:
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");