Commit 6ad7fdecced4647a8e481259fcf229a1339d8dd2

Sam Lantinga 2022-07-18T07:26:29

Fixed infinite loop for values bigger than 0x40000000 Fixes https://github.com/libsdl-org/SDL/issues/5930

diff --git a/src/SDL_utils.c b/src/SDL_utils.c
index e375d74..70cb8ca 100644
--- a/src/SDL_utils.c
+++ b/src/SDL_utils.c
@@ -28,22 +28,22 @@ int SDL_powerof2(int x)
 {
     int value;
 
-    /* We could use this trick for 32-bit values:
-     * value = x;
-     * value -= 1;
-     * value |= value >> 1;
-     * value |= value >> 2;
-     * value |= value >> 4;
-     * value |= value >> 8;
-     * value |= value >> 16;
-     * value += 1;
-     *
-     * ... but this is more readable:
-     */
-    value = 1;
-    while (value < x) {
-        value <<= 1;
+    if (x <= 0) {
+        /* Return some sane value - we shouldn't hit this in our use cases */
+        return 1;
     }
+
+    /* This trick works for 32-bit values */
+    SDL_COMPILE_TIME_ASSERT(SDL_powerof2, sizeof(x) == sizeof(Uint32));
+    value = x;
+    value -= 1;
+    value |= value >> 1;
+    value |= value >> 2;
+    value |= value >> 4;
+    value |= value >> 8;
+    value |= value >> 16;
+    value += 1;
+
     return value;
 }