feature: const variants of into, from, try_from, and default#147
Open
cosmicexplorer wants to merge 7 commits intoillicitonion:mainfrom
Open
feature: const variants of into, from, try_from, and default#147cosmicexplorer wants to merge 7 commits intoillicitonion:mainfrom
cosmicexplorer wants to merge 7 commits intoillicitonion:mainfrom
Conversation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
num_enumis very effective for manipulating data representations at runtime. However, there are some cases where we might want this functionality inconstcontexts, such as when generatingstaticvalues or composingnum_enumtypes into otherCopystructs which we also want to manipulate inconstcontexts.Alternatives
const_trait_implandeffectsare able to avoid the need for parts of this, by makingFrom/Into/Defaultimplsconst-compatible, so for my other work that uses nightly, I actually don't require these at all!constand non-constmethods fornum_enumderives until Rust has developed a more formal mechanism for manipulatingconsteffects.Implementation
Four new derive macros were added, along with auxiliary traits/structs in
lib.rsas needed. Since traits can't defineconst fns, all of these instead generate a method on the enum directly:ConstIntoPrimitive:const_into(self) -> #reprConstFromPrimitive:const_from(#repr) -> SelfConstTryFromPrimitive:const_try_from(#repr) -> Result<Self, ConstTryFromPrimitiveError<Self>>ConstDefault:const_default() -> SelfAdditionally, the
#[num_enum(method_names(...)]attribute was added to the parser, to override the names of generatedconstmethods. This is done because unlike the non-constderives, we do not have a canonical trait to implement, so we risk stomping on users' method names:Result
The boilerplate that
num_enumgenerates no longer has be written by hand when using anum_enumtype inconstcontexts!