Fix signed overflow UB in PseudoRandom::next()

This commit is contained in:
DS 2024-01-19 11:52:53 +01:00 committed by GitHub
parent 7c9706fdcf
commit e416c99419
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -56,8 +56,9 @@ class PseudoRandom {
inline u32 next()
{
m_next = m_next * 1103515245 + 12345;
return (u32)(m_next / 65536) % (RANDOM_RANGE + 1);
m_next = static_cast<u32>(m_next) * 1103515245U + 12345U;
// Signed division is required due to backwards compatibility
return static_cast<u32>(m_next / 65536) % (RANDOM_RANGE + 1U);
}
inline s32 range(s32 min, s32 max)
@ -70,7 +71,7 @@ class PseudoRandom {
PcgRandom, we cannot modify this RNG's range as it would change the
output of this RNG for reverse compatibility.
*/
if ((u32)(max - min) > (RANDOM_RANGE + 1) / 5)
if (static_cast<u32>(max - min) > (RANDOM_RANGE + 1) / 5)
throw PrngException("Range too large");
return (next() % (max - min + 1)) + min;