Crate enum_repr

source ·
Expand description

Generate enum repr conversions compatible with type aliases.

Generate with #[EnumRepr(type = "TYPE")].

Functions generated are

fn repr(&self) -> EnumReprType
fn from_repr(x: EnumReprType) -> Option<Self>

The real enum discriminant still remains isize.

The code generated does not require std.

Examples

extern crate enum_repr;
extern crate libc;

use libc::*;

use enum_repr::EnumRepr;

#[EnumRepr(type = "c_int")]
#[derive(Debug, PartialEq)]
pub enum IpProto {
    IP = IPPROTO_IP,
    IPv6 = IPPROTO_IPV6,
    // …
}

fn main() {
    assert_eq!(IpProto::IP.repr(), IPPROTO_IP);
    assert_eq!(IpProto::from_repr(IPPROTO_IPV6), Some(IpProto::IPv6));
    assert!(IpProto::from_repr(12345).is_none());
}
#[EnumRepr(type = "c_int")]
pub enum InetDomain {
    Inet = 2,
    // …
}

#[EnumRepr(type = "c_int")]
pub enum SocketType {
    Stream = 1,
    // …
}

// …

assert!(
   socket(InetDomain::Inet.repr(), SocketType::Stream.repr(), 0) != -1
);
// compatible with documentation and other attributes

/// Represents a layer 3 network protocol.
#[EnumRepr(type = "c_int")]
#[derive(Debug, PartialEq)]
pub enum IpProto {
    IP = IPPROTO_IP,
    IPv6 = IPPROTO_IPV6,
    // …
}

Out of bound discriminants fail to compile:

#[EnumRepr(type = "u8")]
enum Test {
    A = 256
}

Discriminants of a wrong type fail to compile as well:

const C: u16 = 256;

#[EnumRepr(type = "u8")]
enum Test {
    A = C
}

Attribute Macros

The code generator