#enums #automatic #reverse #try-from #convert #generate #variant

macro convert-enum

Automatically generate From and reverse TryFrom implementations for enums

1 unstable release

0.1.0 Jul 2, 2022

#18 in #try-from

Download history 330/week @ 2023-12-13 357/week @ 2023-12-20 355/week @ 2023-12-27 722/week @ 2024-01-03 428/week @ 2024-01-10 467/week @ 2024-01-17 588/week @ 2024-01-24 340/week @ 2024-01-31 88/week @ 2024-02-07 463/week @ 2024-02-14 260/week @ 2024-02-21 161/week @ 2024-02-28 93/week @ 2024-03-06 134/week @ 2024-03-13 273/week @ 2024-03-20 274/week @ 2024-03-27

793 downloads per month
Used in 17 crates (via atm0s-sdn-network)

Apache-2.0 OR MIT

8KB
87 lines

This crate allows to automatically implement From and reverse TryFrom on suitable enumerations.

In cases where you have an enumeration that wraps multiple different types, and you desire a From or reverse TryFrom implementation for each of them (for example, this is rather common with error handling, when you want to wrap errors from different libraries), this can be quite tedious to do manually.

Using the From and TryInto derive macros from the present crate, this work can be automated.

Example

Define an Error type that can be converted from both std::fmt::Error and std::io::Error (for facilitating use of the question mark operator), and that in addition offers a variant with a custom message that should not be available for automatic conversion:

#[derive(convert_enum::From)]
enum Error {
    #[convert_enum(optout)]
    Custom(Cow<'static, str>),
    Fmt(std::fmt::Error),
    Io(std::io::Error),
}

This results in the following implementations being generated automatically:

impl From<std::fmt::Error> for Error {
    fn from(val: std::fmt::Error) -> Self {
        Self::Fmt(val)
    }
}

impl From<std::io::Error> for Error {
    fn from(val: std::io::Error) -> Self {
        Self::Io(val)
    }
}

Dependencies

~1.5MB
~34K SLoC