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

Joseph Huber via libc-commits libc-commits at lists.llvm.org
Tue Sep 12 13:03:45 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;
----------------
jhuber6 wrote:

I changed this to manually cast, apparently force pushing nukes comments. It's much harder to address comments than it used to be on phab.

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


More information about the libc-commits mailing list