[libc-commits] [libc] [libc] Improve the implementation of the rand() function (PR #66131)

via libc-commits libc-commits at lists.llvm.org
Tue Sep 12 12:57:46 PDT 2023


================
@@ -12,11 +12,13 @@
 
 namespace __llvm_libc {
 
-// This rand function is the example implementation from the C standard. It is
-// not cryptographically secure.
-LLVM_LIBC_FUNCTION(int, rand, (void)) { // RAND_MAX is assumed to be 32767
-  rand_next = rand_next * 1103515245 + 12345;
-  return static_cast<unsigned int>((rand_next / 65536) % 32768);
+// An implementation of the xorshift64star pseudo random number generator. This
+// is a good general purpose generator for most non-cryptographics applications.
+LLVM_LIBC_FUNCTION(int, rand, (void)) {
+  rand_next ^= rand_next >> 12;
+  rand_next ^= rand_next << 25;
+  rand_next ^= rand_next >> 27;
+  return ((rand_next * 0x2545F4914F6CDD1Dull) >> 32) & RAND_MAX;
----------------
michaelrj-google wrote:

The type of this constant should match the type of `rand_next`. This should either be `0x...ul` or `rand_next` should be an `unsigned long long`.

https://github.com/llvm/llvm-project/pull/66131


More information about the libc-commits mailing list