1 | //! # Strum |
2 | //! |
3 | //! [![Build Status](https://travis-ci.org/Peternator7/strum.svg?branch=master)](https://travis-ci.org/Peternator7/strum) |
4 | //! [![Latest Version](https://img.shields.io/crates/v/strum.svg)](https://crates.io/crates/strum) |
5 | //! [![Rust Documentation](https://docs.rs/strum/badge.svg)](https://docs.rs/strum) |
6 | //! |
7 | //! Strum is a set of macros and traits for working with |
8 | //! enums and strings easier in Rust. |
9 | //! |
10 | //! The full version of the README can be found on [Github](https://github.com/Peternator7/strum). |
11 | //! |
12 | //! # Including Strum in Your Project |
13 | //! |
14 | //! Import strum and `strum_macros` into your project by adding the following lines to your |
15 | //! Cargo.toml. `strum_macros` contains the macros needed to derive all the traits in Strum. |
16 | //! |
17 | //! ```toml |
18 | //! [dependencies] |
19 | //! strum = "0.24" |
20 | //! strum_macros = "0.24" |
21 | //! |
22 | //! # You can also access strum_macros exports directly through strum using the "derive" feature |
23 | //! strum = { version = "0.24", features = ["derive"] } |
24 | //! ``` |
25 | //! |
26 | |
27 | #![cfg_attr (not(feature = "std" ), no_std)] |
28 | #![cfg_attr (docsrs, feature(doc_cfg))] |
29 | |
30 | // only for documentation purposes |
31 | pub mod additional_attributes; |
32 | |
33 | #[cfg (feature = "phf" )] |
34 | #[doc (hidden)] |
35 | pub use phf as _private_phf_reexport_for_macro_if_phf_feature; |
36 | |
37 | /// The `ParseError` enum is a collection of all the possible reasons |
38 | /// an enum can fail to parse from a string. |
39 | #[derive (Debug, Clone, Copy, Eq, PartialEq, Hash)] |
40 | pub enum ParseError { |
41 | VariantNotFound, |
42 | } |
43 | |
44 | #[cfg (feature = "std" )] |
45 | impl std::fmt::Display for ParseError { |
46 | fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { |
47 | // We could use our macro here, but this way we don't take a dependency on the |
48 | // macros crate. |
49 | match self { |
50 | ParseError::VariantNotFound => write!(f, "Matching variant not found" ), |
51 | } |
52 | } |
53 | } |
54 | |
55 | #[cfg (feature = "std" )] |
56 | impl std::error::Error for ParseError { |
57 | fn description(&self) -> &str { |
58 | match self { |
59 | ParseError::VariantNotFound => { |
60 | "Unable to find a variant of the given enum matching the string given. Matching \ |
61 | can be extended with the Serialize attribute and is case sensitive." |
62 | } |
63 | } |
64 | } |
65 | } |
66 | |
67 | /// This trait designates that an `Enum` can be iterated over. It can |
68 | /// be auto generated using `strum_macros` on your behalf. |
69 | /// |
70 | /// # Example |
71 | /// |
72 | /// ```rust |
73 | /// # use std::fmt::Debug; |
74 | /// // You need to bring the type into scope to use it!!! |
75 | /// use strum::{EnumIter, IntoEnumIterator}; |
76 | /// |
77 | /// #[derive(EnumIter, Debug)] |
78 | /// enum Color { |
79 | /// Red, |
80 | /// Green { range: usize }, |
81 | /// Blue(usize), |
82 | /// Yellow, |
83 | /// } |
84 | /// |
85 | /// // Iterate over the items in an enum and perform some function on them. |
86 | /// fn generic_iterator<E, F>(pred: F) |
87 | /// where |
88 | /// E: IntoEnumIterator, |
89 | /// F: Fn(E), |
90 | /// { |
91 | /// for e in E::iter() { |
92 | /// pred(e) |
93 | /// } |
94 | /// } |
95 | /// |
96 | /// generic_iterator::<Color, _>(|color| println!("{:?}" , color)); |
97 | /// ``` |
98 | pub trait IntoEnumIterator: Sized { |
99 | type Iterator: Iterator<Item = Self>; |
100 | |
101 | fn iter() -> Self::Iterator; |
102 | } |
103 | |
104 | /// Associates additional pieces of information with an Enum. This can be |
105 | /// autoimplemented by deriving `EnumMessage` and annotating your variants with |
106 | /// `#[strum(message="...")]`. |
107 | /// |
108 | /// # Example |
109 | /// |
110 | /// ```rust |
111 | /// # use std::fmt::Debug; |
112 | /// // You need to bring the type into scope to use it!!! |
113 | /// use strum::EnumMessage; |
114 | /// |
115 | /// #[derive(PartialEq, Eq, Debug, EnumMessage)] |
116 | /// enum Pet { |
117 | /// #[strum(message="I have a dog" )] |
118 | /// #[strum(detailed_message="My dog's name is Spots" )] |
119 | /// Dog, |
120 | /// /// I am documented. |
121 | /// #[strum(message="I don't have a cat" )] |
122 | /// Cat, |
123 | /// } |
124 | /// |
125 | /// let my_pet = Pet::Dog; |
126 | /// assert_eq!("I have a dog" , my_pet.get_message().unwrap()); |
127 | /// ``` |
128 | pub trait EnumMessage { |
129 | fn get_message(&self) -> Option<&'static str>; |
130 | fn get_detailed_message(&self) -> Option<&'static str>; |
131 | |
132 | /// Get the doc comment associated with a variant if it exists. |
133 | fn get_documentation(&self) -> Option<&'static str>; |
134 | fn get_serializations(&self) -> &'static [&'static str]; |
135 | } |
136 | |
137 | /// `EnumProperty` is a trait that makes it possible to store additional information |
138 | /// with enum variants. This trait is designed to be used with the macro of the same |
139 | /// name in the `strum_macros` crate. Currently, the only string literals are supported |
140 | /// in attributes, the other methods will be implemented as additional attribute types |
141 | /// become stabilized. |
142 | /// |
143 | /// # Example |
144 | /// |
145 | /// ```rust |
146 | /// # use std::fmt::Debug; |
147 | /// // You need to bring the type into scope to use it!!! |
148 | /// use strum::EnumProperty; |
149 | /// |
150 | /// #[derive(PartialEq, Eq, Debug, EnumProperty)] |
151 | /// enum Class { |
152 | /// #[strum(props(Teacher="Ms.Frizzle" , Room="201" ))] |
153 | /// History, |
154 | /// #[strum(props(Teacher="Mr.Smith" ))] |
155 | /// #[strum(props(Room="103" ))] |
156 | /// Mathematics, |
157 | /// #[strum(props(Time="2:30" ))] |
158 | /// Science, |
159 | /// } |
160 | /// |
161 | /// let history = Class::History; |
162 | /// assert_eq!("Ms.Frizzle" , history.get_str("Teacher" ).unwrap()); |
163 | /// ``` |
164 | pub trait EnumProperty { |
165 | fn get_str(&self, prop: &str) -> Option<&'static str>; |
166 | fn get_int(&self, _prop: &str) -> Option<usize> { |
167 | Option::None |
168 | } |
169 | |
170 | fn get_bool(&self, _prop: &str) -> Option<bool> { |
171 | Option::None |
172 | } |
173 | } |
174 | |
175 | /// A cheap reference-to-reference conversion. Used to convert a value to a |
176 | /// reference value with `'static` lifetime within generic code. |
177 | #[deprecated ( |
178 | since = "0.22.0" , |
179 | note = "please use `#[derive(IntoStaticStr)]` instead" |
180 | )] |
181 | pub trait AsStaticRef<T> |
182 | where |
183 | T: ?Sized, |
184 | { |
185 | fn as_static(&self) -> &'static T; |
186 | } |
187 | |
188 | /// A trait for capturing the number of variants in Enum. This trait can be autoderived by |
189 | /// `strum_macros`. |
190 | pub trait EnumCount { |
191 | const COUNT: usize; |
192 | } |
193 | |
194 | /// A trait for retrieving the names of each variant in Enum. This trait can |
195 | /// be autoderived by `strum_macros`. |
196 | pub trait VariantNames { |
197 | /// Names of the variants of this enum |
198 | const VARIANTS: &'static [&'static str]; |
199 | } |
200 | |
201 | #[cfg (feature = "derive" )] |
202 | pub use strum_macros::*; |
203 | |
204 | macro_rules! DocumentMacroRexports { |
205 | ($($export:ident),+) => { |
206 | $( |
207 | #[cfg(all(docsrs, feature = "derive" ))] |
208 | #[cfg_attr(docsrs, doc(cfg(feature = "derive" )))] |
209 | pub use strum_macros::$export; |
210 | )+ |
211 | }; |
212 | } |
213 | |
214 | // We actually only re-export these items individually if we're building |
215 | // for docsrs. You can do a weird thing where you rename the macro |
216 | // and then reference it through strum. The renaming feature should be deprecated now that |
217 | // 2018 edition is almost 2 years old, but we'll need to give people some time to do that. |
218 | DocumentMacroRexports! { |
219 | AsRefStr, |
220 | AsStaticStr, |
221 | Display, |
222 | EnumCount, |
223 | EnumDiscriminants, |
224 | EnumIter, |
225 | EnumMessage, |
226 | EnumProperty, |
227 | EnumString, |
228 | EnumVariantNames, |
229 | FromRepr, |
230 | IntoStaticStr, |
231 | ToString |
232 | } |
233 | |