int_to_c_enum/lib.rs
1// SPDX-License-Identifier: MPL-2.0
2
3//! This crate provides a derive macro named TryFromInt. This macro can be used to automatically implement TryFrom trait
4//! for [C-like enums](https://doc.rust-lang.org/stable/rust-by-example/custom_types/enum/c_like.html).
5//!
6//! Currently, this macro only supports enums with [explicit discriminants](https://doc.rust-lang.org/reference/items/enumerations.html#explicit-discriminants).
7//!
8//! Below is a simple example. We derive macro `TryFromInt` for an enum `Color`.
9//! ```rust
10//! use int_to_c_enum::TryFromInt;
11//! #[repr(u8)]
12//! #[derive(TryFromInt, Eq, PartialEq)]
13//! pub enum Color {
14//! Red = 1,
15//! Yellow = 2,
16//! Blue = 3,
17//! }
18//! // Then, we can use method `try_from` for `Color`.
19//! let color = Color::try_from(1).unwrap();
20//! assert!(color == Color::Red);
21//! ```
22//!
23//! The `TryFromInt` macro will automatically implement trait `TryFrom<u8>` for `Color`.
24//! After macro expansion, the generated code looks like as follows:
25//! ```ignore
26//! impl TryFrom<u8> for Color {
27//! type Error = TryFromIntError;
28//! fn try_from(value: u8) -> Result<Self, Self::Error> {
29//! match value {
30//! 1 => Ok(Color::Red),
31//! 2 => Ok(Color::Yellow),
32//! 3 => Ok(Color::Blue),
33//! _ => Err(TryFromIntError::InvalidValue),
34//! }
35//! }
36//! }
37//! ```
38//!
39
40#![cfg_attr(not(test), no_std)]
41
42/// Error type for TryFromInt derive macro
43#[derive(Debug, Clone, Copy)]
44pub enum TryFromIntError {
45 InvalidValue,
46}
47
48#[cfg(feature = "derive")]
49pub use int_to_c_enum_derive::TryFromInt;