Skip to content

Prevent arbitrary objects from conforming to RNG. #36969

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
merged 1 commit into from
Apr 20, 2021
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions stdlib/public/core/Random.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,15 @@ public protocol RandomNumberGenerator {
}

extension RandomNumberGenerator {

// An unavailable default implementation of next() prevents types that do
// not implement the RandomNumberGenerator interface from conforming to the
// protocol; without this, the default next() method returning a generic
// unsigned integer will be used, recursing infinitely and probably blowing
// the stack.
@available(*, unavailable)
public mutating func next() -> UInt64 { fatalError() }

/// Returns a value from a uniform, independent distribution of binary data.
///
/// Use this method when you need random binary data to generate another
Expand Down
21 changes: 21 additions & 0 deletions test/stdlib/Random.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//===--- Random.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-typecheck-verify-swift

struct Jawn { }

// Me, sobbing: "Look, you can't just point at an empty struct and call it a
// RandomNumberGenerator."
// Swift 5.4, pointing at this Jawn: "RNG."
extension Jawn: RandomNumberGenerator { }
// expected-error@-1 {{type 'Jawn' does not conform to protocol 'RandomNumberGenerator'}}
// expected-error@-2 {{unavailable instance method 'next()' was used to satisfy a requirement of protocol 'RandomNumberGenerator'}}