Skip to content

Commit faf89e6

Browse files
stephentyroneairspeedswift
authored andcommitted
Make upperBound != 0 a precondition for RNG.next(upperBound:) (#17627) (#17631)
The function's definition is "Returns a random value that is less than the given upper bound," which cannot possibly be satisfied with upperBound == 0; previously the function returned zero, which was a bug.
1 parent c2e1567 commit faf89e6

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

stdlib/public/core/Random.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,14 @@ extension RandomNumberGenerator {
8989
/// Returns a random value that is less than the given upper bound.
9090
///
9191
/// - Parameter upperBound: The upper bound for the randomly generated value.
92+
/// Must be non-zero.
9293
/// - Returns: A random value of `T` in the range `0..<upperBound`. Every
9394
/// value in the range `0..<upperBound` is equally likely to be returned.
9495
@inlinable
9596
public mutating func next<T: FixedWidthInteger & UnsignedInteger>(
9697
upperBound: T
9798
) -> T {
98-
guard upperBound != 0 else { return 0 }
99+
_precondition(upperBound != 0, "upperBound cannot be zero.")
99100
let tmp = (T.max % upperBound) + 1
100101
let range = tmp == upperBound ? 0 : tmp
101102
var random: T = 0

0 commit comments

Comments
 (0)