enum_is 0.1.1

Enum helper derive: auto-generate is_<variant>() methods for enums
Documentation

enum_is

Procedural macro that generates is_* predicate methods for enum variants.

With #[derive(EnumIs)], every variant of your enum gets an is_<variant>() method (in snake_case) that returns true when self matches that variant.

Works with unit, tuple, and struct variants.


Example

use enum_is::EnumIs;

#[derive(EnumIs, Debug)]
enum Mode {
    Fast,
    Normal,
    Slow,
}

fn handle(mode: Mode) {
    if mode.is_fast() {
        // handle fast mode
    }

    if mode.is_slow() {
        // handle slow mode
    }
}

Generated methods look like:

impl Mode {
    pub fn is_fast(&self) -> bool { /* ... */ }
    pub fn is_normal(&self) -> bool { /* ... */ }
    pub fn is_slow(&self) -> bool { /* ... */ }
}

Installation

In your Cargo.toml:

[dependencies]
enum_is = "0.1"

Then:

use enum_is::EnumIs;

Supported enums

EnumIs works with:

  • Unit variants

    #[derive(EnumIs)]
    enum Status {
        Ok,
        Error,
    }
    
    let s = Status::Ok;
    assert!(s.is_ok());
    assert!(!s.is_error());
    
  • Tuple variants

    #[derive(EnumIs)]
    enum Value {
        Int(i32),
        Pair(u8, u8),
    }
    
    let v = Value::Pair(1, 2);
    assert!(v.is_pair());
    assert!(!v.is_int());
    
  • Struct variants

    #[derive(EnumIs)]
    enum Message {
        Ping,
        Data { id: u64, payload: Vec<u8> },
    }
    
    let m = Message::Data { id: 1, payload: vec![] };
    assert!(m.is_data());
    assert!(!m.is_ping());
    

Naming rules

For each variant, EnumIs generates a method:

  • Method name: is_<variant_name_in_snake_case>

  • Example mappings:

    Variant name Method name
    Fast is_fast()
    PostOnly is_post_only()
    CPU is_cpu()
    HTTPRequestError is_http_request_error()

The methods take &self and return bool.

Internally, the macro uses matches! with:

  • Self::Variant for unit variants
  • Self::Variant(..) for tuple variants
  • Self::Variant { .. } for struct variants

Limitations

  • #[derive(EnumIs)] must be used on enums only.
    Using it on a struct or union will produce a compile error.
  • Method names are generated purely from the variant identifiers; there is no customization (attributes, renames, ignores) yet.