From 375408b826f8c510f1cf3740b46a2bb44804d2cd Mon Sep 17 00:00:00 2001 From: Colin Caine Date: Fri, 10 Feb 2023 15:48:44 +0000 Subject: [PATCH] Make `GetKey(win, KEY_ESCAPE) == PRESS` work `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. --- src/glfw3.jl | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/glfw3.jl b/src/glfw3.jl index 81451b2..8cda544 100644 --- a/src/glfw3.jl +++ b/src/glfw3.jl @@ -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