Skip to content

Conversation

grynspan
Copy link
Contributor

This PR provides an alternate platform-agnostic implementation of swift_stdlib_random() based on C++11's std::random_device. This implementation should be portable even to Embedded Swift, with the significant caveat that there is no way to know at compile time if the random numbers produced are actually non-deterministic. (They should be, but if the current implementation has no suitable RNG, the API doesn't provide a way to detect that statically.)

…d::random_device`.

This PR provides an alternate platform-agnostic implementation of
`swift_stdlib_random()` based on C++11's `std::random_device`. This
implementation should be portable even to Embedded Swift, with the significant
caveat that there is no way to know at compile time if the random numbers
produced are _actually_ non-deterministic. (They _should_ be, but if the current
implementation has no suitable RNG, the API doesn't provide a way to detect that
statically.)
@grynspan grynspan self-assigned this Sep 26, 2025
@grynspan grynspan requested a review from a team as a code owner September 26, 2025 17:31
@grynspan grynspan added improvement standard library Area: Standard library umbrella embedded Embedded Swift labels Sep 26, 2025
@grynspan
Copy link
Contributor Author

@swift-ci test

@grynspan
Copy link
Contributor Author

@swift-ci test

@Azoy
Copy link
Contributor

Azoy commented Sep 27, 2025

Embedded Swift doesn’t currently use swift_stdlib_random from SwiftShims fwiw.

@da-viper
Copy link
Contributor

The embedded version is defined here

@_extern(c, "arc4random_buf")
func arc4random_buf(buf: UnsafeMutableRawPointer, nbytes: Int)
public func swift_stdlib_random(_ buf: UnsafeMutableRawPointer, _ nbytes: Int) {
unsafe arc4random_buf(buf: buf, nbytes: nbytes)
}

@grynspan
Copy link
Contributor Author

grynspan commented Sep 29, 2025

Thanks. I posted this for the sake of discussion.

@grynspan
Copy link
Contributor Author

grynspan commented Oct 1, 2025

To clarify: there was a hallway discussion about needing an implementation of arc4_random() in Embedded Swift precisely because that's the current implementation, so I wrote this up as a "what if we just did this instead?" sort of deal.

Math is hard.
@grynspan
Copy link
Contributor Author

grynspan commented Oct 1, 2025

@swift-ci test

@grynspan grynspan requested a review from rauhul October 1, 2025 15:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
embedded Embedded Swift improvement standard library Area: Standard library umbrella
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

3 participants