enumscribe
This crate provides derive macros for converting between simple enums and strings. It also includes derive macros for serde::Serialize
and serde::Deserialize
for simple enums.
Usage
There are a variety of different traits that you can derive. The "Scribe" traits are for converting from an enum to a string, and the "Unscribe" traits are for converting a string to an enum.
Basic usage
use ;
// Convert an Airport to a &'static str
assert_eq!;
// Convert a &str to a Option<Airport>
assert_eq!;
The #[enumscribe(str = "...")]
allows us to specify what string should be used to represent a particular variant. If this is omitted, the name of the variant
will be used instead.
Case insensitivity
The #[enumscribe(case_insensitive)]
attribute can be used to make the "Unscribe" traits perform case-insensitive matching for a variant:
use TryUnscribe;
assert_eq!;
"other" variant
You can also have a variant which stores strings that could not be matched to any other variant. This is done using the #[enumscribe(other)]
attribute.
The variant should have a single field, which is a String
.
use Cow;
use ;
// Note that we don't need to use an Option anymore!
assert_eq!;
// Unbelievably, websites exist other than github and crates.io
assert_eq!;
// We can't scribe to a &'static str anymore, so we use a Cow<'static, str> instead
assert_eq!;
assert_eq!;
Ignoring variants
If you need to, you can use #[enumscribe(ignore)]
to prevent a variant from being used by Scribe or Unscribe traits.
However, this means that converting the enum to a string can fail, so you must use TryScribe instead of Scribe in this case.
use TryScribeStaticStr;
assert_eq!;
assert_eq!;
Serde
You can derive serde::Serialize
and serde::Deserialize
using the same syntax:
use ;
use ;
// There are probably much more economical ways of making this journey
let flight = Flight ;
let flight_json = r#"{"takeoff":"LHR","landing":"LGW"}"#;
assert_eq!;
assert_eq!;
Traits table
Here is a table to show which traits you should derive, depending on your enum:
ignore used? |
other used? |
Conversion to string | Conversion from string |
---|---|---|---|
No | No | ScribeStaticStr |
TryUnscribe |
No | Yes | ScribeCowStr |
Unscribe |
Yes | No | TryScribeStaticStr |
TryUnscribe |
Yes | Yes | TryScribeCowStr |
Unscribe |
There are also ScribeString
and TryScribeString
traits which can be used in the same situations as ScribeCowStr
and TryScribeCowStr
, respectively.
These traits produce a String
rather than a Cow<'static, str>
, so they will always perform an allocation. Therefore, you should prefer the
ScribeCowStr
traits over the ScribeString
traits, unless you really don't want to use a Cow
for whatever reason.