#enums #discriminant #conversion #derive #safe #convert

macro no-std try-from-discrim

#[derive(TryFrom / From)] using enum discriminants, with fallback support

1 stable release

1.0.0 Sep 29, 2022

#16 in #discriminant

Download history 5/week @ 2024-02-12 15/week @ 2024-02-19 37/week @ 2024-02-26 20/week @ 2024-03-04 25/week @ 2024-03-11 18/week @ 2024-03-18 24/week @ 2024-03-25

91 downloads per month
Used in 3 crates (via gb-cpu-sim)

MPL-2.0 license

22KB
263 lines

derive(TryFrom, From)

This library provides convenient derive macros for the standard library's std::convert::TryFrom and std::convert::From traits.

Example

[dependencies]
try-from-discrim = "1.0"

and then:

#[macro_use] extern crate try_from_discrim;

#[derive(TryFrom)]
#[from(u8)]
enum RegisterIndex {
	B = 0,
	C = 1,
	D = 2,
	E = 3,
	H = 4,
	L = 5,
	HlInd = 6,
	A = 7,
}

(You do not need the extern crate line with Rust 2018 or later.)

The discriminants can be omitted, too! Check the documentation for more information.

Details

  • This crate intentionally stays out of your public API. The provided implementations are identical to as if you had written them by hand, thus switching from handwritten impls to this crate or vice-versa is not a breaking change.
  • Using the standard library conversion traits enables working with more code than deriving a custom trait instead.
  • Non-exhaustive enums can still implement From using a fallback variant.

The generated implementations are compatible with a #[no_std] environment.

License

This crate is licensed under the Mozilla Public License 2.0, see the LICENSE file.

Dependencies

~1.5MB
~32K SLoC