Macro tarantool::define_str_enum
source · macro_rules! define_str_enum { ( $(#![$macro_attr:ident])? $(#[$emeta:meta])* $vis:vis enum $enum:ident { $( $(#[$varmeta:meta])* $variant:ident = $display:literal, )+ } ) => { ... }; (@attr coerce_from_str $($then:tt)*) => { ... }; (@attr $other:ident $($then:tt)*) => { ... }; }
Expand description
Auto-generate enum that maps to a string.
It automatically derives/implements the following traits:
AsRef<str>
,Clone
,Copy
,Into<String>
,Into<&'static str>
,PartialEq
,Eq
,PartialOrd
,Ord
,std::fmt::Debug
,std::fmt::Display
,std::hash::Hash
,std::ops::Deref<Target = str>
,std::str::FromStr
,serde::Deserialize<'de>
,serde::Serialize
,crate::tlua::LuaRead<L>
,crate::tlua::Push<L>
,crate::tlua::PushInto<L>
,crate::tlua::PushOne<L>
,crate::tlua::PushOneInto<L>
,
Example
define_str_enum! {
pub enum Color {
Red = "#FF0000",
Green = "#00FF00",
Blue = "#0000FF",
}
}
This macro generates the following implementation:
pub enum Color {
Red,
Green,
Blue,
}
impl Color {
pub const fn as_str(&self) -> &'static str {
match self {
Self::Red => "#FF0000",
Self::Green => "#00FF00",
Self::Blue => "#0000FF",
}
}
}
Implicit string coercion
#![coerce_from_str]
By default, generated enums are case-sensitive.
This inner attribute enables implicit string coercion when enum is
constructed using FromStr
trait: the string is trimmed and
converted to lower case before matching.
Note, that in that case string variants must be specified in lower case too.
define_str_enum! {
#![coerce_from_str]
pub enum Season {
Summer = "summer",
}
}
use std::str::FromStr;
assert_eq!(Season::from_str("summer"), Ok(Season::Summer));
assert_eq!(Season::from_str("SummeR"), Ok(Season::Summer));
assert_eq!(Season::from_str(" SUMMER "), Ok(Season::Summer));