Cleanup and documentation

rename
Pantonshire 5 years ago
parent b41ea16b82
commit 6dbb36f561

@ -2,11 +2,27 @@
[![Build Status](https://travis-ci.com/Pantonshire/enumscribe.svg?branch=main)](https://travis-ci.com/Pantonshire/enumscribe) [![Build Status](https://travis-ci.com/Pantonshire/enumscribe.svg?branch=main)](https://travis-ci.com/Pantonshire/enumscribe)
This crate provides derive macros for converting between simple enums and strings. It also includes derive macros for [`serde::Serialize`](https://docs.serde.rs/serde/trait.Serialize.html) and [`serde::Deserialize`](https://docs.serde.rs/serde/trait.Deserialize.html) for simple enums. This crate provides derive macros for converting between simple enums and strings. It also includes derive macros for
[`serde::Serialize`](https://docs.serde.rs/serde/trait.Serialize.html) and
[`serde::Deserialize`](https://docs.serde.rs/serde/trait.Deserialize.html) for simple enums.
## Adding enumscribe to your project
Add to your Cargo.toml file:
```toml
[dependencies]
enumscribe = "0.1"
```
Derive macros and [`serde`](https://crates.io/crates/serde) support are enabled by default. They can be disabled by
setting `default-features = false`.
It is also possible to use the `enumscribe_derive` crate on its own without using the `enumscribe` crate. However,
doing so means that you will only be able to derive `serde::Serialize` and `serde::Deserialize`.
## Usage ## 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 There are a variety of different traits that you can derive. The "Scribe" traits are for converting from an enum to a
converting a string to an enum. string, and the "Unscribe" traits are for converting a string to an enum.
### Basic usage ### Basic usage
```rust ```rust
@ -29,11 +45,12 @@ assert_eq!(Airport::Heathrow.scribe(), "LHR");
assert_eq!(Airport::try_unscribe("LGW"), Some(Airport::Gatwick)); assert_eq!(Airport::try_unscribe("LGW"), Some(Airport::Gatwick));
``` ```
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 The `#[enumscribe(str = "...")]` allows us to specify what string should be used to represent a particular variant. If
will be used instead. this is omitted, the name of the variant will be used instead.
### Case insensitivity ### Case insensitivity
The `#[enumscribe(case_insensitive)]` attribute can be used to make the "Unscribe" traits perform case-insensitive matching for a variant: The `#[enumscribe(case_insensitive)]` attribute can be used to make the "Unscribe" traits perform case-insensitive
matching for a variant:
```rust ```rust
use enumscribe::TryUnscribe; use enumscribe::TryUnscribe;
@ -50,8 +67,8 @@ assert_eq!(Website::try_unscribe("GiThUb.CoM"), Some(Website::Github));
``` ```
### "other" variant ### "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. You can also have a variant which stores strings that could not be matched to any other variant. This is done using the
The variant should have a single field, which is a `String`. `#[enumscribe(other)]` attribute. The variant should have a single field, which is a `String`.
```rust ```rust
use std::borrow::Cow; use std::borrow::Cow;

@ -1,6 +1,6 @@
[package] [package]
name = "enumscribe" name = "enumscribe"
version = "0.1.0" version = "0.1.1"
authors = ["Tom Panton <pantonshire@gmail.com>"] authors = ["Tom Panton <pantonshire@gmail.com>"]
edition = "2018" edition = "2018"
license = "MIT" license = "MIT"
@ -11,7 +11,7 @@ categories = ["encoding"]
keywords = ["enum", "derive", "serde"] keywords = ["enum", "derive", "serde"]
[dependencies] [dependencies]
enumscribe_derive = { version = "0.1.0", path = "../enumscribe_derive", optional = true } enumscribe_derive = { version = "0.1.0", path = "../enumscribe_derive", default-features = false, optional = true }
[dev-dependencies] [dev-dependencies]
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }

@ -2,11 +2,27 @@
[![Build Status](https://travis-ci.com/Pantonshire/enumscribe.svg?branch=main)](https://travis-ci.com/Pantonshire/enumscribe) [![Build Status](https://travis-ci.com/Pantonshire/enumscribe.svg?branch=main)](https://travis-ci.com/Pantonshire/enumscribe)
This crate provides derive macros for converting between simple enums and strings. It also includes derive macros for [`serde::Serialize`](https://docs.serde.rs/serde/trait.Serialize.html) and [`serde::Deserialize`](https://docs.serde.rs/serde/trait.Deserialize.html) for simple enums. This crate provides derive macros for converting between simple enums and strings. It also includes derive macros for
[`serde::Serialize`](https://docs.serde.rs/serde/trait.Serialize.html) and
[`serde::Deserialize`](https://docs.serde.rs/serde/trait.Deserialize.html) for simple enums.
## Adding enumscribe to your project
Add to your Cargo.toml file:
```toml
[dependencies]
enumscribe = "0.1"
```
Derive macros and [`serde`](https://crates.io/crates/serde) support are enabled by default. They can be disabled by
setting `default-features = false`.
It is also possible to use the `enumscribe_derive` crate on its own without using the `enumscribe` crate. However,
doing so means that you will only be able to derive `serde::Serialize` and `serde::Deserialize`.
## Usage ## 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 There are a variety of different traits that you can derive. The "Scribe" traits are for converting from an enum to a
converting a string to an enum. string, and the "Unscribe" traits are for converting a string to an enum.
### Basic usage ### Basic usage
```rust ```rust
@ -29,11 +45,12 @@ assert_eq!(Airport::Heathrow.scribe(), "LHR");
assert_eq!(Airport::try_unscribe("LGW"), Some(Airport::Gatwick)); assert_eq!(Airport::try_unscribe("LGW"), Some(Airport::Gatwick));
``` ```
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 The `#[enumscribe(str = "...")]` allows us to specify what string should be used to represent a particular variant. If
will be used instead. this is omitted, the name of the variant will be used instead.
### Case insensitivity ### Case insensitivity
The `#[enumscribe(case_insensitive)]` attribute can be used to make the "Unscribe" traits perform case-insensitive matching for a variant: The `#[enumscribe(case_insensitive)]` attribute can be used to make the "Unscribe" traits perform case-insensitive
matching for a variant:
```rust ```rust
use enumscribe::TryUnscribe; use enumscribe::TryUnscribe;
@ -50,8 +67,8 @@ assert_eq!(Website::try_unscribe("GiThUb.CoM"), Some(Website::Github));
``` ```
### "other" variant ### "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. You can also have a variant which stores strings that could not be matched to any other variant. This is done using the
The variant should have a single field, which is a `String`. `#[enumscribe(other)]` attribute. The variant should have a single field, which is a `String`.
```rust ```rust
use std::borrow::Cow; use std::borrow::Cow;

@ -162,6 +162,8 @@
//! Therefore, you should prefer the `ScribeCowStr` traits over the `ScribeString` traits, unless //! Therefore, you should prefer the `ScribeCowStr` traits over the `ScribeString` traits, unless
//! you *really* don't want to use a `Cow` for whatever reason. //! you *really* don't want to use a `Cow` for whatever reason.
#![deny(missing_docs)]
#[macro_use] #[macro_use]
extern crate enumscribe_derive; extern crate enumscribe_derive;
@ -200,6 +202,11 @@ use std::borrow::Cow;
/// assert_eq!(Airport::UnnamedAirport.scribe(), "UnnamedAirport"); /// assert_eq!(Airport::UnnamedAirport.scribe(), "UnnamedAirport");
/// ``` /// ```
pub trait ScribeStaticStr { pub trait ScribeStaticStr {
/// Converts this enum to a `&'static str`.
///
/// The string returned for a particular variant is determined by the
/// `#[enumscribe(str = "...")]` attribute, or the name of the variant if the attribute
/// is omitted.
fn scribe(&self) -> &'static str; fn scribe(&self) -> &'static str;
} }
@ -236,6 +243,11 @@ pub trait ScribeStaticStr {
/// assert_eq!(Airport::UnnamedAirport.try_scribe(), Some("UnnamedAirport")); /// assert_eq!(Airport::UnnamedAirport.try_scribe(), Some("UnnamedAirport"));
/// ``` /// ```
pub trait TryScribeStaticStr { pub trait TryScribeStaticStr {
/// Converts this enum to a `Option<&'static str>`.
///
/// Calling this method on a variant marked with `#[enumscribe(ignore)]` will return `None`.
/// Calling it on any other variant will return `Some("...")`, where `"..."` is the string
/// specified by the `#[enumscribe(str = "...")]` attribute.
fn try_scribe(&self) -> Option<&'static str>; fn try_scribe(&self) -> Option<&'static str>;
} }
@ -266,6 +278,12 @@ pub trait TryScribeStaticStr {
/// assert_eq!(Airport::Other("STN".to_owned()).scribe(), "STN".to_owned()); /// assert_eq!(Airport::Other("STN".to_owned()).scribe(), "STN".to_owned());
/// ``` /// ```
pub trait ScribeString { pub trait ScribeString {
/// Converts this enum to an allocated `String`.
///
/// When called on a variant marked with `#[enumscribe(other)]`, the variant's field will be
/// returned. For other variants, the string returned is determined by the
/// `#[enumscribe(str = "...")]` attribute, or the name of the variant if the attribute is
/// omitted.
fn scribe(&self) -> String; fn scribe(&self) -> String;
} }
@ -295,6 +313,14 @@ pub trait ScribeString {
/// assert_eq!(Airport::Other("STN".to_owned()).try_scribe(), Some("STN".to_owned())); /// assert_eq!(Airport::Other("STN".to_owned()).try_scribe(), Some("STN".to_owned()));
/// ``` /// ```
pub trait TryScribeString { pub trait TryScribeString {
/// Converts this enum to an allocated `String`.
///
/// Calling this method on a variant marked with `#[enumscribe(ignore)]` will return `None`.
///
/// When called on a variant marked with `#[enumscribe(other)]`, the variant's field will be
/// returned. For other variants, the string returned is determined by the
/// `#[enumscribe(str = "...")]` attribute, or the name of the variant if the attribute is
/// omitted.
fn try_scribe(&self) -> Option<String>; fn try_scribe(&self) -> Option<String>;
} }
@ -338,6 +364,12 @@ pub trait TryScribeString {
/// Cow::Owned::<'static, str>("STN".to_owned())); /// Cow::Owned::<'static, str>("STN".to_owned()));
/// ``` /// ```
pub trait ScribeCowStr { pub trait ScribeCowStr {
/// Converts this enum to a `Cow<'static, str>`.
///
/// When called on a variant marked with `#[enumscribe(other)]`, the variant's field will be
/// returned as a `Cow::Owned`. For other variants, a `Cow::Borrowed` is returned, containing
/// a static string slice determined by the `#[enumscribe(str = "...")]` attribute, or the name
/// of the variant if the attribute is omitted.
fn scribe(&self) -> Cow<'static, str>; fn scribe(&self) -> Cow<'static, str>;
} }
@ -381,6 +413,14 @@ pub trait ScribeCowStr {
/// Some(Cow::Owned::<'static, str>("STN".to_owned()))); /// Some(Cow::Owned::<'static, str>("STN".to_owned())));
/// ``` /// ```
pub trait TryScribeCowStr { pub trait TryScribeCowStr {
/// Converts this enum to a `Option<Cow<'static, str>>`.
///
/// Calling this method on a variant marked with `#[enumscribe(ignore)]` will return `None`.
///
/// When called on a variant marked with `#[enumscribe(other)]`, the variant's field will be
/// returned as a `Cow::Owned`. For other variants, a `Cow::Borrowed` is returned, containing
/// a static string slice determined by the `#[enumscribe(str = "...")]` attribute, or the name
/// of the variant if the attribute is omitted.
fn try_scribe(&self) -> Option<Cow<'static, str>>; fn try_scribe(&self) -> Option<Cow<'static, str>>;
} }
@ -425,6 +465,11 @@ pub trait TryScribeCowStr {
/// assert_eq!(Airport::unscribe("stn"), Airport::Other("stn".to_owned())); /// assert_eq!(Airport::unscribe("stn"), Airport::Other("stn".to_owned()));
/// ``` /// ```
pub trait Unscribe: Sized { pub trait Unscribe: Sized {
/// Converts the given string to an enum variant.
///
/// The given string is matched against the `#[enumscribe(str = "...")]` attribute for each
/// variant to determine which variant to return. If there was no successful match, the
/// variant marked with `#[enumscribe(other)]` will be returned instead.
fn unscribe(to_unscribe: &str) -> Self; fn unscribe(to_unscribe: &str) -> Self;
} }
@ -462,5 +507,12 @@ pub trait Unscribe: Sized {
/// assert_eq!(Airport::try_unscribe("stn"), None); /// assert_eq!(Airport::try_unscribe("stn"), None);
/// ``` /// ```
pub trait TryUnscribe: Sized { pub trait TryUnscribe: Sized {
/// Converts the given string to an enum variant, or `None` if the conversion was not
/// successful.
///
/// The given string is matched against the `#[enumscribe(str = "...")]` attribute for each
/// variant to determine which variant to return. If there was no successful match, the
/// variant marked with `#[enumscribe(other)]` will be returned instead. If there is no
/// variant marked with `#[enumscribe(other)]`, then `None` will be returned.
fn try_unscribe(to_unscribe: &str) -> Option<Self>; fn try_unscribe(to_unscribe: &str) -> Option<Self>;
} }

@ -1,6 +1,6 @@
[package] [package]
name = "enumscribe_derive" name = "enumscribe_derive"
version = "0.1.0" version = "0.1.1"
authors = ["Tom Panton <pantonshire@gmail.com>"] authors = ["Tom Panton <pantonshire@gmail.com>"]
edition = "2018" edition = "2018"
license = "MIT" license = "MIT"
@ -17,4 +17,5 @@ syn = "1.0"
quote = "1.0" quote = "1.0"
[features] [features]
default = ["serde"]
serde = [] serde = []

@ -2,11 +2,27 @@
[![Build Status](https://travis-ci.com/Pantonshire/enumscribe.svg?branch=main)](https://travis-ci.com/Pantonshire/enumscribe) [![Build Status](https://travis-ci.com/Pantonshire/enumscribe.svg?branch=main)](https://travis-ci.com/Pantonshire/enumscribe)
This crate provides derive macros for converting between simple enums and strings. It also includes derive macros for [`serde::Serialize`](https://docs.serde.rs/serde/trait.Serialize.html) and [`serde::Deserialize`](https://docs.serde.rs/serde/trait.Deserialize.html) for simple enums. This crate provides derive macros for converting between simple enums and strings. It also includes derive macros for
[`serde::Serialize`](https://docs.serde.rs/serde/trait.Serialize.html) and
[`serde::Deserialize`](https://docs.serde.rs/serde/trait.Deserialize.html) for simple enums.
## Adding enumscribe to your project
Add to your Cargo.toml file:
```toml
[dependencies]
enumscribe = "0.1"
```
Derive macros and [`serde`](https://crates.io/crates/serde) support are enabled by default. They can be disabled by
setting `default-features = false`.
It is also possible to use the `enumscribe_derive` crate on its own without using the `enumscribe` crate. However,
doing so means that you will only be able to derive `serde::Serialize` and `serde::Deserialize`.
## Usage ## 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 There are a variety of different traits that you can derive. The "Scribe" traits are for converting from an enum to a
converting a string to an enum. string, and the "Unscribe" traits are for converting a string to an enum.
### Basic usage ### Basic usage
```rust ```rust
@ -29,11 +45,12 @@ assert_eq!(Airport::Heathrow.scribe(), "LHR");
assert_eq!(Airport::try_unscribe("LGW"), Some(Airport::Gatwick)); assert_eq!(Airport::try_unscribe("LGW"), Some(Airport::Gatwick));
``` ```
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 The `#[enumscribe(str = "...")]` allows us to specify what string should be used to represent a particular variant. If
will be used instead. this is omitted, the name of the variant will be used instead.
### Case insensitivity ### Case insensitivity
The `#[enumscribe(case_insensitive)]` attribute can be used to make the "Unscribe" traits perform case-insensitive matching for a variant: The `#[enumscribe(case_insensitive)]` attribute can be used to make the "Unscribe" traits perform case-insensitive
matching for a variant:
```rust ```rust
use enumscribe::TryUnscribe; use enumscribe::TryUnscribe;
@ -50,8 +67,8 @@ assert_eq!(Website::try_unscribe("GiThUb.CoM"), Some(Website::Github));
``` ```
### "other" variant ### "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. You can also have a variant which stores strings that could not be matched to any other variant. This is done using the
The variant should have a single field, which is a `String`. `#[enumscribe(other)]` attribute. The variant should have a single field, which is a `String`.
```rust ```rust
use std::borrow::Cow; use std::borrow::Cow;

@ -195,7 +195,7 @@ pub(crate) fn parse_enum(data: &DataEnum) -> MacroResult<Enum> {
}.insert(lowercase_name); }.insert(lowercase_name);
// Return an error if the variant has any fields // Return an error if the variant has any fields
if variant.fields.len() != 0 { if !variant.fields.is_empty() {
let variant_ident = variant.ident.to_string(); let variant_ident = variant.ident.to_string();
return Err(MacroError::new( return Err(MacroError::new(
format!( format!(

@ -1,7 +1,10 @@
//! Derive macros for the traits provided by `enumscribe`, to help you easily convert your enums //! Derive macros for the traits provided by [`enumscribe`](https://docs.rs/enumscribe), to
//! to strings and vice-versa. //! help you easily convert your enums to strings and vice-versa.
//! //!
//! See the documentation for the `enumscribe` crate for usage examples. //! See the [documentation for the `enumscribe` crate](https://docs.rs/crate/enumscribe) for usage
//! examples.
#![deny(missing_docs)]
use proc_macro::TokenStream; use proc_macro::TokenStream;
@ -270,7 +273,7 @@ fn gen_unscribe_match<F, G, E>(
Ok(main_match) Ok(main_match)
} }
/// Derives `enumscribe::ScribeStaticStr` for an enum. This allows the enum to be converted to /// Derives [`enumscribe::ScribeStaticStr`](https://docs.rs/enumscribe/latest/enumscribe/trait.ScribeStaticStr.html) for an enum. This allows the enum to be converted to
/// a `&'static str` using the `scribe()` method. /// a `&'static str` using the `scribe()` method.
/// ///
/// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant /// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant
@ -321,7 +324,7 @@ pub fn derive_scribe_static_str(input: TokenStream) -> TokenStream {
) )
} }
/// Derives `enumscribe::TryScribeStaticStr` for an enum. This allows the enum to be converted to /// Derives [`enumscribe::TryScribeStaticStr`](https://docs.rs/enumscribe/latest/enumscribe/trait.TryScribeStaticStr.html) for an enum. This allows the enum to be converted to
/// a `Option<&'static str>` using the `try_scribe()` method. /// a `Option<&'static str>` using the `try_scribe()` method.
/// ///
/// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant /// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant
@ -359,7 +362,7 @@ pub fn derive_try_scribe_static_str(input: TokenStream) -> TokenStream {
) )
} }
/// Derives `enumscribe::ScribeString` for an enum. This allows the enum to be converted to /// Derives [`enumscribe::ScribeString`](https://docs.rs/enumscribe/latest/enumscribe/trait.ScribeString.html) for an enum. This allows the enum to be converted to
/// a `String` using the `scribe()` method. /// a `String` using the `scribe()` method.
/// ///
/// This behaves almost identically to [`ScribeCowStr`](derive.ScribeCowStr.html), except the /// This behaves almost identically to [`ScribeCowStr`](derive.ScribeCowStr.html), except the
@ -394,7 +397,7 @@ pub fn derive_scribe_string(input: TokenStream) -> TokenStream {
) )
} }
/// Derives `enumscribe::TryScribeString` for an enum. This allows the enum to be converted to /// Derives [`enumscribe::TryScribeString`](https://docs.rs/enumscribe/latest/enumscribe/trait.TryScribeString.html) for an enum. This allows the enum to be converted to
/// a `Option<String>` using the `try_scribe()` method. /// a `Option<String>` using the `try_scribe()` method.
/// ///
/// This behaves almost identically to [`TryScribeCowStr`](derive.TryScribeCowStr.html), except the /// This behaves almost identically to [`TryScribeCowStr`](derive.TryScribeCowStr.html), except the
@ -427,7 +430,7 @@ pub fn derive_try_scribe_string(input: TokenStream) -> TokenStream {
) )
} }
/// Derives `enumscribe::ScribeCowStr` for an enum. This allows the enum to be converted to /// Derives [`enumscribe::ScribeCowStr`](https://docs.rs/enumscribe/latest/enumscribe/trait.ScribeCowStr.html) for an enum. This allows the enum to be converted to
/// a `Cow<'static, str>` using the `scribe()` method. /// a `Cow<'static, str>` using the `scribe()` method.
/// ///
/// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant /// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant
@ -474,7 +477,7 @@ pub fn derive_scribe_cow_str(input: TokenStream) -> TokenStream {
) )
} }
/// Derives `enumscribe::TryScribeCowStr` for an enum. This allows the enum to be converted to /// Derives [`enumscribe::TryScribeCowStr`](https://docs.rs/enumscribe/latest/enumscribe/trait.TryScribeCowStr.html) for an enum. This allows the enum to be converted to
/// a `Option<Cow<'static, str>>` using the `try_scribe()` method. /// a `Option<Cow<'static, str>>` using the `try_scribe()` method.
/// ///
/// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant /// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string the variant
@ -520,7 +523,7 @@ pub fn derive_try_scribe_cow_str(input: TokenStream) -> TokenStream {
) )
} }
/// Derives `enumscribe::Unscribe` for an enum. This allows a `&str` to be converted to the /// Derives [`enumscribe::Unscribe`](https://docs.rs/enumscribe/latest/enumscribe/trait.Unscribe.html) for an enum. This allows a `&str` to be converted to the
/// enum using the `unscribe()` associated function. /// enum using the `unscribe()` associated function.
/// ///
/// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string should /// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string should
@ -564,7 +567,7 @@ pub fn derive_unscribe(input: TokenStream) -> TokenStream {
) )
} }
/// Derives `enumscribe::TryUnscribe` for an enum. This allows a `&str` to be converted to an /// Derives [`enumscribe::TryUnscribe`](https://docs.rs/enumscribe/latest/enumscribe/trait.TryUnscribe.html) for an enum. This allows a `&str` to be converted to an
/// `Option` of the enum using the `try_unscribe()` associated function. /// `Option` of the enum using the `try_unscribe()` associated function.
/// ///
/// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string should /// You may annotate variants with `#[enumscribe(str = "foo")]` to specify what string should

Loading…
Cancel
Save