This could be extremely useful for use with C-like enums if the compiler is smart enough to recognize valid ranges, much like it does when checking for exhaustiveness in match statements.
The simplest case is a #[repr(T)] enum where every possible value in T is defined in the enum. In practice this would be useful mainly for repr(u8) because of the current require to specify enum items for each individual value.
A slightly more advanced case is a #[repr(T)] enum where every value between 0 and N are defined. Currently it is only possible to convert between enums with the same ranges either through exhaustive match statements or using transmute. Compiler-generated implementations of FromBits / IntoBits or Compatible would eliminate a huge amount of unsafe boilerplate code and be the first step into turning C-like enums into a general-purpose ranged value type.
For instance, bobbin-bits defines enums for U1 to U32 (covering 1-bit to 32-bit values) and ranges R1 to R32 (covering ranges for 1…N). These are used for modeling bit fields and for type-checked indexing of small fixed arrays, but using them with enums requires manually implementing From and To traits to do conversions, which is tedious and mistake-prone.
It would be far more useful if I could do something like this and have the compiler check that Compatible<U4>
is valid:
fn takes_u4<T: Compatible<U4>>(v: T) {
let value: U4 = v.safe_transmute();
do_something(value)
}
enum ThingWithSixteenItems {
Item0 = 0,
Item1 = 1,
...
Item15 = 15,
}
impl Compatible<U4> for ThingWithSixteenItems {}
or even better, have the Compatible<U4>
trait automatically derived for any enum matching the valid range of U4.