[][src]Crate encap_enum

A type-safe encapsulated enum useful for interacting with C bitmasks, abbreviating a group of constants with the same type, and an enumerator instance that can be safely assigned too regardless of whether it is in the enum.

Internally encap_enum uses a tuple struct, therefore to access the value of a variant use tuple accessor syntax .0.

Terms such as enum, and variant are used throughout the doc even though the internal representation can be different, and the reason is because rust's canonical enum is used internally when omitting explicit declarations. In other words it acts like an enum, yet it is composed of many different constructs.

Example

The encap_enum! allows for bit flags and other common manipulations of data below:

encap_enum!{
    enum Flags {
        A = 1 + 4 + 8,
        B = 2,
        C = A | B, // C = 15
    }
}

The flags can be assigned to constants outside the enum since all the enum members are internally constants:

const VALUE: isize = MoreFlags::Omega.0;
const OTHER: MoreFlags = MoreFlags::Sigma;
encap_enum!{
    enum MoreFlags {
        Omega = 1,
        Sigma = 2,
        Delta = 3,
    }
}

The enum_encap! macro also supports enumeration like a normal fieldless enum by tapping into rust's own enum. The internal enum is under the non-public namespace __encap_enum, so it will likely be out of the way for the most part.

#[macro_use]
extern crate encap_enum;

encap_enum!{
    enum OtherFlags {
        Alpha,
        Beta,
        Charlie,
    }
}
fn main() {
    println!("{}", OtherFlags::Alpha.0);
}

Visibility

The visibility for both the value and the data itself can be changed:

encap_enum!{
    pub enum PublicFlags: pub(in crate) u32 {
        Alpha,
        Beta,
        Charlie,
    }
}

Attributes

Can be used pretty much anywhere in the macro except right under the declaration (See Corner Cases section at bottom for more details).

Trait Implementations

The following traits are derived:

  • Debug
  • Copy
  • Clone
  • PartialEq
  • Eq
  • PartialOrd
  • Hash

Operators

The following operators are implemented:

  • BitOr
  • Add
  • BitAnd
  • BitXor
  • Div
  • Mul
  • Shl
  • Shr
  • Sub
  • Rem
  • Not
  • From

Methods

  • iter: An iterator over all the variants.

Corner Cases

Currently attributes cannot be placed before the first variant.

The #[repr(C)] attribute will work and make the enum more ffi compatible, however #[repr(u8)], #[repr(u16)], etc. will not compile because the internal representation that it will apply to is a tuple stuct. The equivalent of #[repr(u32)], which would apply on an enum would look like this on an encap_enum! declaration:

encap_enum!{
    #[repr(C)]
    enum Flag: u32 {
        // variants here.
    }
}

Macros

encap_enum

A macro for bit flags and enumerations.