SDL: Added check for n<0 in SDL_rand_n()

From 8a80f41b779f8da4f9ad937151d0e25f9058023f Mon Sep 17 00:00:00 2001
From: John Kaniarz <[EMAIL REDACTED]>
Date: Wed, 19 Jun 2024 16:51:21 -0400
Subject: [PATCH] Added check for n<0 in SDL_rand_n()

---
 src/stdlib/SDL_random.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/src/stdlib/SDL_random.c b/src/stdlib/SDL_random.c
index 642f3a72fe22f..2007431733b35 100644
--- a/src/stdlib/SDL_random.c
+++ b/src/stdlib/SDL_random.c
@@ -67,6 +67,14 @@ Sint32 SDL_rand_n(Sint32 n)
     // fixed point number. Multiply by the 31.0 bit n to get a 31.32 bit
     // result. Shift right by 32 to get the 31 bit integer that we want.
 
+    if (n < 0) {
+        // The algorithm looks like it works for numbers < 0 but it has an
+        // infintesimal chance of returning a value out of range.
+        // Returning -SDL_rand_n(abs(n)) blows up at INT_MIN instead.
+        // It's easier to just say no.
+        return 0;
+    }
+
     // On 32-bit arch, the compiler will optimize to a single 32-bit multiply
     Uint64 val = (Uint64)SDL_rand_bits() * n;
     return (Sint32)(val >> 32);