Fixed infinite loop for values bigger than 0x40000000 Fixes https://github.com/libsdl-org/SDL/issues/5930
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
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;
}