This is an automated email from the ASF dual-hosted git repository.

astitcher pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/qpid-proton.git


The following commit(s) were added to refs/heads/main by this push:
     new a58e66c  PROTON-2396: Use random_device for seed initialization in 
uuid.cpp
a58e66c is described below

commit a58e66ce3e42937a1b22e0c741834bc6eb0a9797
Author: Rakhi Kumari <[email protected]>
AuthorDate: Wed Nov 3 18:46:04 2021 +0530

    PROTON-2396: Use random_device for seed initialization in uuid.cpp
    
    Closes #340
---
 cpp/src/uuid.cpp | 36 ++++++++++++++++++------------------
 1 file changed, 18 insertions(+), 18 deletions(-)

diff --git a/cpp/src/uuid.cpp b/cpp/src/uuid.cpp
index ec3880c..150d6c8 100644
--- a/cpp/src/uuid.cpp
+++ b/cpp/src/uuid.cpp
@@ -22,10 +22,15 @@
 #include "proton/uuid.hpp"
 #include "proton/types_fwd.hpp"
 
+#include <algorithm>
+#include <chrono>
+#include <climits>
 #include <cstdlib>
 #include <ctime>
-#include <sstream>
+#include <functional>
 #include <iomanip>
+#include <random>
+#include <sstream>
 
 #if defined(_WIN32)
 #include <process.h>
@@ -39,19 +44,19 @@ namespace proton {
 
 namespace {
 
+thread_local std::independent_bits_engine<std::mt19937, CHAR_BIT, unsigned 
int> engine = [] {
+  // A hash of time, PID and random_device to produce an unsigned integer
+  // for seeding the engine.
+  std::seed_seq seq{
+      (unsigned 
long)std::chrono::system_clock::now().time_since_epoch().count(),
+      (unsigned long)GETPID(),
+      (unsigned long)std::random_device{}()};
 
-// Seed the random number generated once at startup.
-struct seed {
-    seed() {
-        // A hash of time and PID, time alone is a bad seed as programs started
-        // within the same second will get the same seed.
-        unsigned long secs = time(0);
-        unsigned long pid = GETPID();
-        std::srand(((secs*181)*((pid-83)*359))%104729);
-    }
-} seed_;
+  return
+      std::independent_bits_engine<std::mt19937, CHAR_BIT, unsigned int>(seq);
+}();
 
-}
+} // namespace
 
 uuid uuid::copy() {
     uuid u;
@@ -70,12 +75,7 @@ uuid uuid::copy(const char* bytes) {
 
 uuid uuid::random() {
     uuid bytes;
-    int r = std::rand();
-    for (size_t i = 0; i < bytes.size(); ++i ) {
-        bytes[i] = r & 0xFF;
-        r >>= 8;
-        if (!r) r = std::rand();
-    }
+    std::generate(bytes.begin(), bytes.end(), std::ref(engine));
 
     // From RFC4122, the version bits are set to 0100
     bytes[6] = (bytes[6] & 0x0F) | 0x40;

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to