#enums #inner #proc-macro #access #field #deriving #accessor

macro enum-as-inner

A proc-macro for deriving inner field accessor functions on enums

13 releases

0.6.1 Sep 9, 2024
0.6.0 May 30, 2023
0.5.2 May 27, 2023
0.5.1 Aug 6, 2022
0.2.1 Dec 9, 2018

#34 in Procedural macros

Download history 464460/week @ 2024-08-21 455859/week @ 2024-08-28 510119/week @ 2024-09-04 466537/week @ 2024-09-11 475895/week @ 2024-09-18 507924/week @ 2024-09-25 541558/week @ 2024-10-02 545648/week @ 2024-10-09 592116/week @ 2024-10-16 581002/week @ 2024-10-23 664499/week @ 2024-10-30 689318/week @ 2024-11-06 737820/week @ 2024-11-13 704083/week @ 2024-11-20 495397/week @ 2024-11-27 513017/week @ 2024-12-04

2,577,160 downloads per month
Used in 1,658 crates (95 directly)

MIT/Apache

17KB
265 lines

enum-as-inner

A deriving proc-macro for generating functions to automatically give access to the inner members of enum.

Basic unnamed field case

The basic case is meant for single item enums, like:

use enum_as_inner::EnumAsInner;

#[derive(Debug, EnumAsInner)]
enum OneEnum {
    One(u32),
}

where the inner item can be retrieved with the as_*()/as_*_mut() or with the into_*() functions:

let one = OneEnum::One(1);

assert_eq!(*one.as_one().unwrap(), 1);
assert_eq!(one.into_one().unwrap(), 1);

let mut one = OneEnum::One(2);

assert_eq!(*one.as_one().unwrap(), 1);
assert_eq!(*one.as_one_mut().unwrap(), 1);
assert_eq!(one.into_one().unwrap(), 1);

where the result is either a reference for inner items or a tuple containing the inner items.

Unit case

This will return true if enum's variant matches the expected type

use enum_as_inner::EnumAsInner;

#[derive(EnumAsInner)]
enum UnitVariants {
    Zero,
    One,
    Two,
}

let unit = UnitVariants::Two;

assert!(unit.is_two());

Mutliple, unnamed field case

This will return a tuple of the inner types:

use enum_as_inner::EnumAsInner;

#[derive(Debug, EnumAsInner)]
enum ManyVariants {
    One(u32),
    Two(u32, i32),
    Three(bool, u32, i64),
}

And can be accessed like:

let mut many = ManyVariants::Three(true, 1, 2);

assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64));
assert_eq!(many.as_three_mut().unwrap(), (&mut true, &mut 1_u32, &mut 2_i64));
assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64));

Multiple, named field case

This will return a tuple of the inner types, like the unnamed option:

use enum_as_inner::EnumAsInner;

#[derive(Debug, EnumAsInner)]
enum ManyVariants {
    One{ one: u32 },
    Two{ one: u32, two: i32 },
    Three{ one: bool, two: u32, three: i64 },
}

And can be accessed like:

let mut many = ManyVariants::Three{ one: true, two: 1, three: 2 };

assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64));
assert_eq!(many.as_three_mut().unwrap(), (&mut true, &mut 1_u32, &mut 2_i64));
assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64));

Dependencies

~245–690KB
~16K SLoC