value_from_type_traits/
lib.rs

1//! Traits used in conjunction with the [`value_from_type_macros`] crate.
2
3#![doc(html_root_url = "https://docs.rs/value_from_type_traits")]
4
5/// Returns an enum variant for the generic argument.
6/// 
7/// This trait is similar to [From] without needing to provide an
8/// actual (l-)value.   
9/// As with the [From] trait, developers are encouraged to implement
10/// this trait for their types or equivalently use the procedural macro attribute
11/// [`value_from_type_macros::value_from_type`] found within the [value_from_type_macros] crate.
12/// 
13/// 
14/// # Examples
15/// 
16/// ``` 
17/// # use value_from_type_traits::{FromType, IntoEnum};
18/// #[derive(Debug)]
19/// struct X;
20/// #[derive(Debug, PartialEq)]
21/// enum StructVariants { X_V };
22/// 
23/// impl FromType<X> for StructVariants {
24/// 	fn from_type() -> Self {
25/// 		StructVariants::X_V
26/// 	}
27/// }
28/// 
29/// assert_eq!(StructVariants::X_V, <StructVariants as FromType<X>>::from_type());
30/// assert_eq!(StructVariants::X_V, X::into_enum()); 
31/// ```
32/// 
33/// 
34/// [From]: std::convert::From
35/// [value_from_type_macros]: value_from_type_macros
36pub trait FromType<T> {
37    fn from_type() -> Self;
38}
39
40/// Reflexive implementation on [`FromType`].
41/// 
42/// Developers are encouraged to implement [`FromType`], because [`IntoEnum`]
43/// is automatically derived from that definition.
44pub trait IntoEnum<E> {
45    fn into_enum() -> E;
46}
47
48impl<T, E> IntoEnum<E> for T
49where
50    E: FromType<T>,
51{
52    fn into_enum() -> E {
53        <E as FromType<T>>::from_type()
54    }
55}