Fix: Avoid arithmetic overflow in RandIntFromRange

- Use big.Int for span calculation instead of int64 cast
- Prevents silent overflow on 32-bit systems or extreme input ranges
- Handles edge cases more robustly
This commit is contained in:
Gurjit-30 2026-04-12 17:20:14 +05:30
parent 41b204cef5
commit d5cc54fcf7

View file

@ -17,8 +17,13 @@ func RandIntFromRange(r Range) int {
if r.End-r.Begin <= 0 {
return r.Begin
}
max := int64((r.End - r.Begin) + 1)
n, err := rand.Int(rand.Reader, big.NewInt(max))
// Use big.Int for span calculation to avoid arithmetic overflow
begin := big.NewInt(int64(r.Begin))
end := big.NewInt(int64(r.End))
max := new(big.Int).Sub(end, begin)
max.Add(max, big.NewInt(1))
n, err := rand.Int(rand.Reader, max)
if err != nil {
// Fallback to begin value if crypto/rand fails (rare)
return r.Begin