From 54c9725fff6340286e74d347389b86aae6993710 Mon Sep 17 00:00:00 2001 From: Neil Date: Sat, 6 Jun 2020 16:13:43 +1000 Subject: Backport: Avoid type-pun union when converting from RGBA colour to DWORD as this may be undefined or implementation defined behaviour. Drop some casts by hoisting out part of dwordMultiplied. Backport of changeset 8289:a53064f376c5. --- win32/PlatWin.cxx | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/win32/PlatWin.cxx b/win32/PlatWin.cxx index 629a49963..09cb2f517 100644 --- a/win32/PlatWin.cxx +++ b/win32/PlatWin.cxx @@ -743,23 +743,19 @@ void AllFour(DWORD *pixels, int width, int height, int x, int y, DWORD val) noex pixels[(height-1-y)*width+width-1-x] = val; } -DWORD dwordFromBGRA(byte b, byte g, byte r, byte a) noexcept { - union { - byte pixVal[4]; - DWORD val; - } converter; - converter.pixVal[0] = b; - converter.pixVal[1] = g; - converter.pixVal[2] = r; - converter.pixVal[3] = a; - return converter.val; +constexpr DWORD dwordFromBGRA(byte b, byte g, byte r, byte a) noexcept { + return (a << 24) | (r << 16) | (g << 8) | b; +} + +constexpr byte AlphaScaled(unsigned char component, unsigned int alpha) noexcept { + return static_cast(component * alpha / 255); } DWORD dwordMultiplied(ColourDesired colour, unsigned int alpha) noexcept { return dwordFromBGRA( - static_cast(colour.GetBlue() * alpha / 255), - static_cast(colour.GetGreen() * alpha / 255), - static_cast(colour.GetRed() * alpha / 255), + AlphaScaled(colour.GetBlue(), alpha), + AlphaScaled(colour.GetGreen(), alpha), + AlphaScaled(colour.GetRed(), alpha), static_cast(alpha)); } -- cgit v1.2.3