Crate c_enum

source ·
Expand description

A macro for easily defining structs that act like C enums.

The c_enum! macro generates structs that behave roughly like a C enum: they have a set of constants that have integer values but can be assigned integer values that don’t correspond to any of the existing names.

Examples

use c_enum::c_enum;

c_enum! {
    #[derive(Copy, Clone, PartialEq, Eq, Hash)]
    pub enum MyEnum: u32 {
        A,
        B = 5,
    }
}

let v1 = MyEnum::A;       // declared variant
let v2 = MyEnum::from(3); // also supports variants that are not declared

match v1 { // we can match if we derive PartialEq
    MyEnum::A => println!("got an A"),
    MyEnum::B => println!("got a B"),

    // We still need to handle other variants
    _ => println!("got another variant"),
}

Visibility

The c_enum! macro supports visibility, just like you would do for a normal rust enum.

mod example {
    c_enum! {
        pub enum Enum1: u8 {
            A,
        }

        enum Enum2: u8 {
            B,
        }
    }
}

let val1 = example::Enum1::A;
let val2 = example::Enum2::B; // error: struct `Enum2` is private

Attributes

Attributes can be added to the generated type or variants as normal. Note that the variants are converted to constants so macros expecting an enum variant will not work.

Representation

It is valid to add a #[repr(C)] or #[repr(transparent)] attribute to the generated type. The generated type is guaranteed to be a newtype whose only member is the inner type.

Value Assignment

By default, enum values are assigned like they would be for a C enum: the first variant is 0 and subsequent variants increase by 1 unless assigned a value.

c_enum! {
    pub enum Enum: u32 {
        A,     // value of 0
        B,     // value of 1
        C = 5, // value of 5
        D,     // value of 6
    }
}

Non-String Inner Types

It is also possible to define enum types whose inner value is not an integer.

c_enum! {
    pub enum StringEnum: &'static str {
        Hello = "Hello",
        World = "World",
    }
}

Note that at this time generics are not supported so any inner value type must be both concrete and 'static. Furthermore, you will need to assign a value to each variant of such an enum.

What’s implemented by c_enum!

The c_enum! macro implements some traits by default, but leaves the rest available for you to choose the semantics of the rest.

  • CEnum which contains some common methods for all c-like enums.

Formatting

Conversion

  • From to convert from the inner type and vice versa.

Non-Integer Enums

Creating

Generated Code

c_enum! {
    #[repr(transparent)]
    #[derive(Copy, Clone, PartialEq, Eq, Hash)]
    enum Enum: u32 {
        A,
        B = 5,
    }
}

is expanded into (roughly)

#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
struct Enum(u32);

impl Enum {
    pub const A: Self = Self(0);
    pub const B: Self = Self(5);
}

impl core::fmt::Debug for Enum
where
    u32: core::cmp::PartialEq
{
    ...
}

// more trait impls...

Motivation

When writing bindings for C libraries which use enums there are a few options for declaring rust versions of C enums.

  • Use a rust enum.
  • Use a raw integer and a bunch of constants.
  • Use a newtype and a set of constants.

All of them have use cases for which they are valid:

  • Rust enums work when calling from rust code into C code. The one caveat here being that if the underlying C library adds a new variant but the rust wrapper does not then users of the rust library are stuck. Another case that is valid is if it is known that no new variants will be added to the underlying C enum and the library is ok with either UB or doing conversions at the API boundary.
  • Raw integers and constants is useful for autogenerated bindings that want to exactly match the layout of the C headers.
  • A newtype + constants is suitable for the remaining cases. It still behaves similar to a rust enum but matches the actual semantics of C enums. It also continues to work if the C library adds new variants and the rust wrapper is not updated.

This crate is a generator for the third option.

Modules

  • This module shows an example of code generated by the macro.

Macros

  • The macro used to generate the C enum structure.

Traits

  • A trait that is automatically implemented for all C enums.