#macro-derive #enums #integer #int #unit #converting #called

int-to-c-enum

TryFromInt - A convenient derive macro for converting an integer to an enum

1 unstable release

0.1.0 Jul 1, 2024

#1414 in Rust patterns

Download history 58/week @ 2024-07-27 47/week @ 2024-08-03 64/week @ 2024-08-10 47/week @ 2024-08-17 84/week @ 2024-08-24 37/week @ 2024-08-31 37/week @ 2024-09-07 72/week @ 2024-09-14 83/week @ 2024-09-21 114/week @ 2024-09-28 49/week @ 2024-10-05 56/week @ 2024-10-12 60/week @ 2024-10-19 79/week @ 2024-10-26 55/week @ 2024-11-02 37/week @ 2024-11-09

238 downloads per month
Used in 2 crates (via ostd)

MPL-2.0 license

5KB

TryFromInt - A convenient derive macro for converting an integer to an enum

Quick Start

To use this crate, first add this crate to your Cargo.toml.

[dependencies]
int-to-c-enum = "0.1.0"

You can use this macro for a C-like enum.

use int_to_c_enum::TryFromInt;
#[repr(u8)]
#[derive(TryFromInt, Debug)]
pub enum Color {
    Red = 1,
    Blue = 2,
    Green = 3,
}

Then, you can use try_from function for this enum.

fn main() {
    let color = Color::try_from(1).unwrap();
    println!("color = {color:?}"); // color = Red;
}

Introduction

This crate provides a derive procedural macro named TryFromInt. This macro will automatically implement TryFrom trait for enums that meet the following requirements:

  1. The enum must have a primitive repr, i.e., the enum should have attribute like #[repr(u8)], #[repr(u32)], etc. The type parameter of TryFrom will be the repr, e.g., in the QuickStart example, the macro will implment TryFrom<u8> for Color.
  2. The enum must consist solely of unit variants, which is called units only enum. Each field should have an explicit discriminant.

Dependencies

~105KB