from_str_sequential/
lib.rs

1#![doc = include_str!("../README.md")]
2
3pub use from_str_sequential_derive::FromStrSequential;
4
5/// sibling trait of `FromStr`. Used on enums with unit and un-named variants, and try to convert the string to each variant sequentially (from top to bottom variant). For unit variant,
6/// the string must be the variant name (case-insentive). For un-named variants, the string must match the `FromStr` implementation of the un-named type.
7/// ## Example
8/// ```
9/// use from_str_sequential::FromStrSequential;
10/// #[derive(Debug, FromStrSequential, PartialEq, Eq)]
11/// enum Foo {
12///     Bar,
13///     Baz(usize),
14/// }
15/// assert_eq!(Foo::Bar, Foo::from_str_sequential("bar").unwrap());
16/// assert_eq!(Foo::Bar, Foo::from_str_sequential("BaR").unwrap());
17/// assert_eq!(Foo::Baz(100), Foo::from_str_sequential("100").unwrap());
18/// ```
19pub trait FromStrSequential: Sized {
20    type Err;
21
22    fn from_str_sequential(s: &str) -> Result<Self, Self::Err>;
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[derive(FromStrSequential, Debug)]
30    enum Pancakes {
31        Cookie,
32        Banana,
33    }
34
35    #[derive(FromStrSequential, Debug, PartialEq, Eq)]
36    enum Foo {
37        Bar,
38        Baz(usize),
39    }
40
41    #[test]
42    fn test_from_str_sequential() {
43        assert_eq!(Foo::Bar, Foo::from_str_sequential("bar").unwrap());
44        assert_eq!(Foo::Bar, Foo::from_str_sequential("BaR").unwrap());
45        assert_eq!(Foo::Baz(100), Foo::from_str_sequential("100").unwrap());
46    }
47}