Skip to content

Commit 99c521b

Browse files
Prevent arbitrary objects from conforming to RNG. (#36969) (#36982)
Me, sobbing: "Look, you can't just point at an empty struct and call it a RandomNumberGenerator." Swift 5.4, pointing at anything: "RNG."
1 parent 61bcb39 commit 99c521b

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

stdlib/public/core/Random.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,15 @@ public protocol RandomNumberGenerator {
6464
}
6565

6666
extension RandomNumberGenerator {
67+
68+
// An unavailable default implementation of next() prevents types that do
69+
// not implement the RandomNumberGenerator interface from conforming to the
70+
// protocol; without this, the default next() method returning a generic
71+
// unsigned integer will be used, recursing infinitely and probably blowing
72+
// the stack.
73+
@available(*, unavailable)
74+
public mutating func next() -> UInt64 { fatalError() }
75+
6776
/// Returns a value from a uniform, independent distribution of binary data.
6877
///
6978
/// Use this method when you need random binary data to generate another

test/stdlib/Random.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//===--- Random.swift -----------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2021 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
// RUN: %target-typecheck-verify-swift
13+
14+
struct Jawn { }
15+
16+
// Me, sobbing: "Look, you can't just point at an empty struct and call it a
17+
// RandomNumberGenerator."
18+
// Swift 5.4, pointing at this Jawn: "RNG."
19+
extension Jawn: RandomNumberGenerator { }
20+
// expected-error@-1 {{type 'Jawn' does not conform to protocol 'RandomNumberGenerator'}}
21+
// expected-error@-2 {{unavailable instance method 'next()' was used to satisfy a requirement of protocol 'RandomNumberGenerator'}}

0 commit comments

Comments
 (0)