This PR adds the annotation #[enumset(repr = "u8")] to specify the in-memory representation of EnumSet.
This has several effects:
The enum type will implement the new trait EnumSetTypeWithRepr along with EnumSetType and EnumSetTypePrivate. EnumSetTypeWithRepr has an associated type Repr, which equals EnumSetTypePrivate::Repr.
EnumSet gains the new methods as_repr, from_repr, from_repr_unchecked, try_from_repr, and from_repr_truncated. These methods convert to/from Repr without widening or narrowing. as_repr and from_repr_unchecked are also zero-cost and guaranteed not to fail, panic, or truncate any bits (but from_repr_unchecked is unsafe).
The in-memory representation of EnumSet becomes predictable: it is guaranteed to be whatever type is given in repr. This makes it sound to pass EnumSet across FFI boundaries.
I expect this will be useful for FFI and serialization.
My use-case is using EnumSet with the prost library. prost can't generate structs with custom types like EnumSet, only standard types like u32. To use EnumSet with it, I have to convert the EnumSet to u32, then insert that into the struct field. With #[enumset(repr = "u32")], the derive macro will verify at compile time that all of my enum variants will actually fit into the struct field, instead of only finding out at run time when EnumSet::as_u32 panics.
This PR adds the annotation
#[enumset(repr = "u8")]
to specify the in-memory representation ofEnumSet
.This has several effects:
EnumSetTypeWithRepr
along withEnumSetType
andEnumSetTypePrivate
.EnumSetTypeWithRepr
has an associated typeRepr
, which equalsEnumSetTypePrivate::Repr
.EnumSet
gains the new methodsas_repr
,from_repr
,from_repr_unchecked
,try_from_repr
, andfrom_repr_truncated
. These methods convert to/fromRepr
without widening or narrowing.as_repr
andfrom_repr_unchecked
are also zero-cost and guaranteed not to fail, panic, or truncate any bits (butfrom_repr_unchecked
isunsafe
).EnumSet
becomes predictable: it is guaranteed to be whatever type is given inrepr
. This makes it sound to passEnumSet
across FFI boundaries.I expect this will be useful for FFI and serialization.
My use-case is using
EnumSet
with theprost
library.prost
can't generate structs with custom types likeEnumSet
, only standard types likeu32
. To useEnumSet
with it, I have to convert theEnumSet
tou32
, then insert that into the struct field. With#[enumset(repr = "u32")]
, the derive macro will verify at compile time that all of my enum variants will actually fit into the struct field, instead of only finding out at run time whenEnumSet::as_u32
panics.