Skip to content

[4.2] Make upperBound != 0 a precondition for RNG.next(upperBound:) (#17627) #17631

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion stdlib/public/core/Random.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,14 @@ extension RandomNumberGenerator {
/// Returns a random value that is less than the given upper bound.
///
/// - Parameter upperBound: The upper bound for the randomly generated value.
/// Must be non-zero.
/// - Returns: A random value of `T` in the range `0..<upperBound`. Every
/// value in the range `0..<upperBound` is equally likely to be returned.
@inlinable
public mutating func next<T: FixedWidthInteger & UnsignedInteger>(
upperBound: T
) -> T {
guard upperBound != 0 else { return 0 }
_precondition(upperBound != 0, "upperBound cannot be zero.")
let tmp = (T.max % upperBound) + 1
let range = tmp == upperBound ? 0 : tmp
var random: T = 0
Expand Down