[swift-evolution] [Proposal] Random Unification

Chris Lattner clattner at nondot.org
Wed Oct 4 23:11:59 CDT 2017


On Oct 4, 2017, at 7:26 PM, Xiaodi Wu via swift-evolution <swift-evolution at swift.org> wrote:
> * Remove the range-less function. Naive users often write things like `Int.random() % 100`, which unbeknownst to them is biased. Providing only the ranged interface nudges naive users toward correct usage. 
> 
> * Provide an "easy" way to get some random bytes instead of a random number. Perhaps a Data initializer that returns random-filled bytes of the requested length. This helps make up for the lack of a range-less function on FixedWidthInteger.
> 
> The "easy" functions should get the best names: Int.random(in:), Data.random(length:), etc. The fundamental CSPRNG interface should have an interface that is less friendly and less discoverable.
> 
> Agree, this is a very tractable set of functions for an initial implementation. In fact, with these primitives and maybe some shuffling and choosing conveniences in the stdlib, I see the remainder as useful-to-haves that may or may not be critical for inclusion in the stdlib vs more appropriate for a dedicated math library (more to follow on that thought in a little while).
> 
> To sum up my thoughts so far in code, building on previous comments from others, this would be a nice set of random APIs, IMO:
> 
> ```
> extension Int {
>   static func random(in range: Countable{Closed}Range<Int>) -> Int
> }

Nice.  Should these be initializers like:

extension Int {
  init(randomIn: Countable{Closed}Range<Int>)
}

or some other spelling?

> extension Data {
>   static func random(byteCount: Int) -> Data
> }

Similarly:

extension Data {
  init(randomByteCount: Int)
}


> 
> extension UnsafeMutableRawPointer {
>   func copyRandomBytes(count: Int) throws
> }
> // This function is to be the most primitive of the random APIs, and will throw if there is insufficient entropy.
> 
> extension UnsafeMutableRawBufferPointer {
>   func copyRandomBytes() throws
> }
> // Just as UMRBP.copyBytes(from:) parallels UMRP.copyBytes(from:count:), we offer this convenience here.
> ```

I’m not sure what the semantics of these APIs are, but with the appropriate doc comment they’re probably great :-)

-Chris


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171004/0dedc4cf/attachment.html>


More information about the swift-evolution mailing list