Skip to content

Commit 075b550

Browse files
committed
Merge pull request #100067 from aaronp64/randi_range_overflow
Fix `RandomPCG::random(int, int)` overflow bug
2 parents 051712d + 1089f61 commit 075b550

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

core/math/random_pcg.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,15 @@ int RandomPCG::random(int p_from, int p_to) {
8080
if (p_from == p_to) {
8181
return p_from;
8282
}
83-
return int(rand(uint32_t(Math::abs(p_from - p_to)) + 1U)) + MIN(p_from, p_to);
83+
84+
int64_t min = MIN(p_from, p_to);
85+
int64_t max = MAX(p_from, p_to);
86+
uint32_t diff = static_cast<uint32_t>(max - min);
87+
88+
if (diff == UINT32_MAX) {
89+
// Can't add 1 to max uint32_t value for inclusive range, so call rand without passing bounds.
90+
return static_cast<int64_t>(rand()) + min;
91+
}
92+
93+
return static_cast<int64_t>(rand(diff + 1U)) + min;
8494
}

0 commit comments

Comments
 (0)