Skip to content

Implement Into/From<u8>for MouseButton and Into/From<u16> for KeyCode - #657

Open
andybarron wants to merge 7 commits into
not-fl3:masterfrom
andybarron:master
Open

Implement Into/From<u8>for MouseButton and Into/From<u16> for KeyCode#657
andybarron wants to merge 7 commits into
not-fl3:masterfrom
andybarron:master

Conversation

@andybarron

@andybarron andybarron commented Aug 8, 2026

Copy link
Copy Markdown

best reviewed with whitespace diffs disabled (link).

summary

this PR implements conversion between MouseButton/KeyCode and their underlying primitive types (with tests). this should make it easier to serialize & deserialize mouse/key codes for rebinding game controls, etc.

the specific trait implementations in question are:

  • impl From<u8> for MouseButton
  • impl From<MouseButton> for u8
  • impl From<u16> for KeyCode
  • impl From<KeyCode> for u16

implementation notes

  • the conversion impls are generated by wrapping the enum definition in a simple declarative macro called convertible_enum!. currently, rust lets you safely convert an enum to its underlying repr, but not vice versa (other than transmute tricks which cause UB on invalid values). to the best of my knowledge, this is the best solution in terms of minimizing boilerplate and not bringing in something like num_enum (which pulls in proc_macro, which is just overkill for this IMO).
  • i chose to implement From rather than TryFrom since the enums in question both have an Unknown variant to catch invalid values already. with TryFrom, a successful conversion could still have Unknown as the value, which felt weird and redundant to me.

@not-fl3

not-fl3 commented Aug 8, 2026

Copy link
Copy Markdown
Owner

Thanks for PR!

I am not neccesserily against the change, but I want to mention that num_enum has 10x+ more lines of code that miniquad and all miniquad's current dependencies. (it brings essentially fully featured rust parser for its proc-macro stuff).
I would suggest hand-implementing MouseButton -> u8 function with just 3 line match statement.

@andybarron

andybarron commented Aug 8, 2026

Copy link
Copy Markdown
Author

@not-fl3 i had a brain blast last night and realized i could just do this with macro_rules!. better now? :)

EDIT: the macro added a level of indentation so it's easier to review with whitespace off: link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants