Skip to content

Commit

Permalink
Make GetKey(win, KEY_ESCAPE) == PRESS work
Browse files Browse the repository at this point in the history
`GetKey` is defined below to return a `Bool`, but in the documentation
it is defined as returning `PRESS` or `RELEASE`. In C that doesn't
matter, but in Julia these are different types and so e.g.
`GLFW.GetKey(window, GLFW.KEY_ESCAPE)) == GLFW.PRESS` will always return
false.

This method tells Julia how to compare an `Action` and a `Bool` so that
code calling `GetKey` as documented will work as expected.

Julia will do slightly more work when comparing `Bool` and `Action` than
when comparing two `Bool`s because it will expand the Bool to 32 bits
first. This could be avoided by defining the basetype of the `Action`
enum as `UInt8`, but that would be a breaking change if arrays of
`Action` are ever passed to C (I don't think they would be, but idk).

I tried to persuade Julia to omit the expansion to 32 bits, but I
couldn't find anything that worked. Closest was
`b == unsafe_trunc(Bool, a)`, but that still emits more instructions
than comparing two `Bool`s.
  • Loading branch information
cmcaine committed Feb 10, 2023
1 parent e8d5815 commit 375408b
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/glfw3.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
PRESS = 1
REPEAT = 2
end
# GetKey is defined below to return a Bool, but in the documentation it is
# defined as returning PRESS or RELEASE. In C that doesn't matter, but in
# Julia these are different types and so e.g.
# `GLFW.GetKey(window, GLFW.KEY_ESCAPE)) == GLFW.PRESS` will always return
# false.
#
# This method tells Julia how to compare an Action and a Bool so that code
# calling GetKey as documented will work as expected.
Base.(==)(b::Bool, a::Action) = b == Integer(a)

@enum Key::Cint begin
# Unknown key
Expand Down

0 comments on commit 375408b

Please sign in to comment.