convertable-errors

Crates.ioconvertable-errors
lib.rsconvertable-errors
version0.1.0
sourcesrc
created_at2021-06-23 18:06:25.764784
updated_at2021-06-23 18:06:25.764784
descriptionThis crate defines an ergonomic macro for deriving From conversions for variants of Rust enums.
homepage
repositoryhttps://github.com/dowlandaiello/convertable-errors
max_upload_size
id414069
size8,791
Dowland Aiello (dowlandaiello)

documentation

README

convertable-errors

This crate defines a macro for deriving From conversions for variants of Rust enums. For example:

enum ForeignType;

enum MyEnum {
    Variant(ForeignType)
}

impl From<ForeignType> for MyEnum {
    fn from(v: ForeignType) -> Self {
        Self::Variant(v)
    }
}

This is how we would typically define conversions from foreign types to enum variants that contain those foreign types. But convertable-errors provides a declarative Rust macro to generate these conversions for us. Convertable errors can be used to generate these types of conversions for any type of Rust enum (excluding enums with struct variants, for now), but my main use case is error-like enums.

Using convertable-errors, we can generate From<T> definitions for our enum variants like so:

enum ForeignType;

convertable_error! {
    enum MyEnum {
        (Variant(ForeignType), [(ForeignType, Self::Variant)]
    }
}

The syntax for defining a convertable enum with convertable-errors is as follows:

  • Each variant of an enum must be wrapped in a tuple: enum MyError { (Variant(ForeignType)), (Variant1) }
  • The first member of the tuple represents your variant. At the moment, only tuple variants and unit variants are supported bc I'm a lazy fuck.
  • The second member of the tuple (optional) represents the types that can be converted into that variant: enum MyError { (Variant(ForeignType), [ ... ]), (Variant1) }
  • The members of the convertable types array are each tuples representing the foreign type that can be converted into your enum and the closure or variant to apply the foreign value to: [(ForeignType, Self::Variant)]. Internally, this second member can be a closure |x| Self::Variant(x), a unit variant closure |_| Self::Variant1, or simply a variant identifier where the value of the foreign type will be stored: Self::Variant. In practice, you can use this macro for any enum, but I find it most useful for Error-like enums.

NOTE: This isn't a serious project, I might have made some mistakes, so feel free to open a PR :) This is just a helpful snippet that I use and felt like sharing.

Commit count: 7

cargo fmt