#enums #int #traits #integer #derive #macro

from_int

A package to easily add a from_int method to enums with #[derive(FromInt)]

3 releases

Uses old Rust 2015

0.1.2 Mar 28, 2018
0.1.1 Mar 27, 2018
0.1.0 Mar 27, 2018

#2383 in Rust patterns

Download history 6/week @ 2024-02-15 7/week @ 2024-02-22 1/week @ 2024-02-29 3/week @ 2024-03-07 4/week @ 2024-03-14 27/week @ 2024-03-28 25/week @ 2024-04-04

52 downloads per month

MIT license

4KB

from_int   Latest Version

Motivation

This crate provides an easy way to convert a plain integer into an enum type, something that rust can currently do natively in the opposite direction.

Usage

Usage of from_int is extremely simple. Just add it as a dependency to your crate, then:

extern crate from_int; // contains the trait
#[macro_use] extern crate from_int_derive; // contains the macro

use from_int::FromInt;

#[derive(FromInt, Debug, PartialEq)]
enum TestEnum {
    VariantOne = 1,
    VariantTwo = 2,
    VariantThree = 528,
    VariantX = 999
}

assert_eq!(TestEnum::VariantOne, TestEnum::from_int(1).unwrap());
assert_eq!(TestEnum::VariantTwo, TestEnum::from_int(2).unwrap());
assert_eq!(TestEnum::VariantThree, TestEnum::from_int(528).unwrap());
assert_eq!(TestEnum::VariantX, TestEnum::from_int(999).unwrap());

// This would panic:
assert_eq!(None, TestEnum::from_int(123));

Dependencies

~2MB
~46K SLoC