#enum #anonymous #sum #structural #ad-hoc

enumx

Structural enum implemented in enum exchange

8 releases

✓ Uses Rust 2018 edition

0.3.1 Jun 28, 2020
0.3.0 Jan 17, 2019
0.2.1 Dec 17, 2018
0.1.1 Dec 4, 2018
0.0.1 Nov 20, 2018

#83 in Rust patterns

38 downloads per month
Used in cex

MIT license

26KB
462 lines

Motivation

Emulating structural enums in Rust.

Usage

  1. Add this crate to Cargo.toml

Cargo.toml:

[dependencies.enumx]
version = "0.3.1"

src/lib.rs:

use enumx::*;
  1. Use Enum!(A,B,..) to define a structural enum, the variants of which are A, B, .. etc.
let a: Enum!(i32,String) = 42.into_enum();

let b = <Enum!(i32,String,bool)>::from_variant( "the answer".to_owned() );
  1. Use .from_enumx()/.into_enumx() to convert between structural enums and/or their variants.
let c: Enum!(i32,String,bool) = 42.into_enumx();

let d: Enum!(i32,String,bool) = a.into_enumx();

let e = <Enum!(i32,String,bool)>::from_enumx( 42 );

let f = <Enum!(i32,bool,String)>::from_enumx( e );
  1. Use #[ty_pat] match to do pattern matching against an Enum!(A, B, ..), the arms of which are not variants but types A, B, .. etc. The fn containing the match expression must be tagged #[enumx].
#[enumx] fn foo( input: Enum!(String,i32) ) {
    #[ty_pat] match input {
        String(s) => println!( "it's string:{}", s ),
        i32(i) => println!( "it's i32:{}", i ),
    }
}
  • Use #[ty_pat(gen_variants)] to generate missing types in Enum!()
#[enumx] fn foo( input: Enum!(String,i32) ) -> Enum!(String,i32) {
    #[ty_pat(gen_variants)] match input {
        i32(i) => (i+1).into_enumx(),
        // generated arm: String(s) => s.into_enumx(),
    }
}
  • Use #[ty_pat(gen A,B,..)] to generate A,B,.. etc
#[enumx] fn foo( input: Enum!(String,i32) ) -> Enum!(String,i32) {
    #[ty_pat(gen String)] match input {
        i32(i) => (i+1).into_enumx(),
        // generated arm: String(s) => s.into_enumx(),
    }
}
  • Use TyPat to wrap types that are not paths, e.g. references, (), in a #[ty_pat] match's arm:
#[enumx] fn bar( input: Enum!(&'static str,i32) ) {
    #[ty_pat] match input {
        TyPat::<&'static str>(s) => println!( "it's static str:{}", s ),
        i32(i) => println!( "it's i32:{}", i ),
    }
}
  1. Use #[derive( EnumX )] to make user-defined enums exchangable from/to other Enum!()s or #[derive(EnumX)] enums.
#[derive( EnumX )]
enum Info {
    Code(i32),
    Text(&'static str),
}

let info: Info = 42.into_enum();

let a: Enum!(&'static str, i32) = "a".into_enum();

let info: Info = a.into_enumx();

let b: Enum!(&'static str, i32) = info.into_enumx();

Notice

All the features provided by this crate work with stable Rust, including #[enumx] closures/let-bindings and #[ty_pat] match.

License

Licensed under MIT.

Dependencies

~385–710KB
~17K SLoC