Fixed infinite loop for values bigger than 0x40000000

Fixes https://github.com/libsdl-org/SDL/issues/5930
This commit is contained in:
Sam Lantinga 2022-07-18 07:26:29 -07:00
parent 986818143d
commit 6ad7fdecce

View file

@ -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;
}