1 // Wrap this in two cfg_attrs so that it continues to parse pre-1.54.0. 2 // See https://github.com/rust-lang/rust/issues/82768 3 #![cfg_attr(feature = "external_doc", cfg_attr(all(), doc = include_str!("../README.md")))] 4 #![cfg_attr( 5 not(feature = "external_doc"), 6 doc = "See <https://docs.rs/num_enum> for more info about this crate." 7 )] 8 #![cfg_attr(not(feature = "std"), no_std)] 9 10 pub use ::num_enum_derive::{ 11 Default, FromPrimitive, IntoPrimitive, TryFromPrimitive, UnsafeFromPrimitive, 12 }; 13 14 use ::core::fmt; 15 16 pub trait FromPrimitive: Sized { 17 type Primitive: Copy + Eq; 18 from_primitive(number: Self::Primitive) -> Self19 fn from_primitive(number: Self::Primitive) -> Self; 20 } 21 22 pub trait TryFromPrimitive: Sized { 23 type Primitive: Copy + Eq + fmt::Debug; 24 25 const NAME: &'static str; 26 try_from_primitive(number: Self::Primitive) -> Result<Self, TryFromPrimitiveError<Self>>27 fn try_from_primitive(number: Self::Primitive) -> Result<Self, TryFromPrimitiveError<Self>>; 28 } 29 30 #[derive(::derivative::Derivative)] 31 #[derivative( // use derivative to remove incorrect bound on `Enum` parameter. See https://github.com/rust-lang/rust/issues/26925 32 Debug(bound = ""), 33 Clone(bound = ""), 34 Copy(bound = ""), 35 PartialEq(bound = ""), 36 Eq(bound = "") 37 )] 38 pub struct TryFromPrimitiveError<Enum: TryFromPrimitive> { 39 pub number: Enum::Primitive, 40 } 41 42 impl<Enum: TryFromPrimitive> fmt::Display for TryFromPrimitiveError<Enum> { fmt(&self, stream: &'_ mut fmt::Formatter<'_>) -> fmt::Result43 fn fmt(&self, stream: &'_ mut fmt::Formatter<'_>) -> fmt::Result { 44 write!( 45 stream, 46 "No discriminant in enum `{name}` matches the value `{input:?}`", 47 name = Enum::NAME, 48 input = self.number, 49 ) 50 } 51 } 52 53 #[cfg(feature = "std")] 54 impl<Enum: TryFromPrimitive> ::std::error::Error for TryFromPrimitiveError<Enum> {} 55