#enums #boolean #derive #proc-macro #variant-name

macro boolenum

Derive From<bool> and Into<bool> for your boolean enums

1 unstable release

0.1.0 Jun 19, 2020

#15 in #variant-name

Download history 1724/week @ 2024-11-17 1878/week @ 2024-11-24 1909/week @ 2024-12-01 2350/week @ 2024-12-08 1708/week @ 2024-12-15 1066/week @ 2024-12-22 1000/week @ 2024-12-29 2637/week @ 2025-01-05 2430/week @ 2025-01-12 2916/week @ 2025-01-19 2563/week @ 2025-01-26 3439/week @ 2025-02-02 3308/week @ 2025-02-09 4494/week @ 2025-02-16 4331/week @ 2025-02-23 4347/week @ 2025-03-02

16,595 downloads per month
Used in 3 crates (via oq3_semantics)

MIT/Apache

8KB
71 lines

boolenum

BoolEnum is a derive macro to create ergonomic boolean enums with less boilerplate. It generates From<bool>, Into<bool> and Not impls for your enum.

use boolenum::BoolEnum;

// Variant names can be Yes and No (in any order) ...
#[derive(BoolEnum)]
enum UseColors {
    No,
    Yes,
}

// or True and False
#[derive(BoolEnum)]
enum ShowExpired {
    True,
    False,
}

fn print_things(use_colors: UseColors, show_expired: ShowExpired) {
    if use_colors.into() { // Into<bool>
      // ...
    }
}

fn main() {
    print_things(UseColors::Yes, ShowExpired::False)
}

Boolean enums are useful for differentiating between boolean arguments to a function, so you can write something like encode(&bytes, Encrypt::Yes, Compress::No) instead of encode(&bytes, true, false).

Goes well with structopt, for type-safe handling of command-line flags:

use boolenum::BoolEnum;
use structopt::StructOpt;

#[derive(BoolEnum)]
enum Verbose { No, Yes }
#[derive(BoolEnum)]
enum Colors { No, Yes }

#[derive(StructOpt)]
struct Opt {
    #[structopt(short, long, parse(from_flag))]
    verbose: Verbose, // works because Verbose implements From<bool>
    #[structopt(short, long, parse(from_flag))]
    colors: Colors,
}

fn main() {
    let opt = Opt::from_args();
    do_thing(opt.verbose, opt.colors);
}

fn do_thing(verbose: Verbose, colors: Colors) {
    if verbose.into() { }
    if colors.into() { }
}

BoolEnum works on enums with two unit variants, named either Yes and No, or True and False. The order of the variants in the enum doesn't matter.

License: MIT OR Apache-2.0

Dependencies

~1.5MB
~39K SLoC