File: README.md

package info (click to toggle)
rust-enum-primitive 0.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, sid, trixie
  • size: 124 kB
  • sloc: makefile: 2
file content (49 lines) | stat: -rw-r--r-- 1,309 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# enum_primitive [![Build Status](https://travis-ci.org/andersk/enum_primitive-rs.svg?branch=master)](https://travis-ci.org/andersk/enum_primitive-rs)

This crate exports a macro `enum_from_primitive!` that wraps an
`enum` declaration and automatically adds an implementation of
`num::FromPrimitive` (reexported here), to allow conversion from
primitive integers to the enum.  It therefore provides an
alternative to the built-in `#[derive(FromPrimitive)]`, which
requires the unstable `std::num::FromPrimitive` and is disabled in
Rust 1.0.

## Documentation

https://andersk.github.io/enum_primitive-rs/enum_primitive/

## Usage

Add the following to your `Cargo.toml` file:

```
[dependencies]
enum_primitive = "*"
```

Import the crate using `#[macro_use] extern crate enum_primitive`, and
wrap your `enum` declaration inside the `enum_from_primitive!` macro.

## Example

```rust
#[macro_use] extern crate enum_primitive;
extern crate num;
use num::FromPrimitive;

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum FooBar {
    Foo = 17,
    Bar = 42,
    Baz,
}
}

fn main() {
    assert_eq!(FooBar::from_i32(17), Some(FooBar::Foo));
    assert_eq!(FooBar::from_i32(42), Some(FooBar::Bar));
    assert_eq!(FooBar::from_i32(43), Some(FooBar::Baz));
    assert_eq!(FooBar::from_i32(91), None);
}
```