convert-enum 0.1.0

Automatically generate From and reverse TryFrom implementations for enums
Documentation
  • Coverage
  • 100%
    3 out of 3 items documented3 out of 3 items with examples
  • Size
  • Source code size: 19.83 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 295.19 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 4s Average build duration of successful builds.
  • all releases: 4s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • alois31/convert-enum
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • alois31

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)
    }
}