#macros #enum #addr

addr_of_enum

Get address of fields in enum item using stable Rust

6 releases

0.1.5 Feb 12, 2024
0.1.4 Jan 10, 2024

#167 in Memory management

Download history 118/week @ 2023-12-31 40/week @ 2024-01-07 32/week @ 2024-01-14 31/week @ 2024-01-28 1/week @ 2024-02-04 77/week @ 2024-02-11 234/week @ 2024-02-18

343 downloads per month
Used in fast_enum_conversion

MIT license

5KB
71 lines

addr_of_enum

This crate provides #[derive(AddrOfEnum)] and addr_of_enum! macro to get a field pointer of specified variant without creating an intermediated reference. It works like std::ptr::addr_of!, but works only on enums.

This macro is zero-cost, which means that it calculates without minimum cost in release mode.

It also works on variables which has uninhabited types.

Example

# use addr_of_enum::{addr_of_enum, AddrOfEnum};

#[derive(AddrOfEnum)]
#[repr(C)]
enum MyEnum {
    E1(usize, u8),
    E2 {
        item1: u32,
        item2: u8,
    }
}

let e = MyEnum::E1(1, 2);
let _: *const usize = addr_of_enum!(&e, E1, 0);
let _: *const u32 = addr_of_enum!(&e, E2, item1);

Limitations

For now, the macros cannot be used in const context.

Dependencies

~1.5MB
~35K SLoC