Skip to content

Commit f073866

Browse files
committed
better random string generator function
1 parent 9848616 commit f073866

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

src/utils.h

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
#endif
4040

4141
#include <math.h>
42+
#include <random>
4243
#include <string>
4344
#include <iostream>
4445
#include <fstream>
@@ -48,21 +49,22 @@
4849
//--------------------------------------------------------------
4950
inline std::string random_string( size_t length ){
5051

51-
srand(ofGetElapsedTimeMillis());
52+
static auto& chrs = "0123456789"
53+
"abcdefghijklmnopqrstuvwxyz"
54+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
55+
"!?*+{}[]()=$-_";
5256

53-
auto randchar = []() -> char
54-
{
55-
const char charset[] =
56-
"0123456789"
57-
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
58-
"abcdefghijklmnopqrstuvwxyz"
59-
"!¿?*+{}[]%&()=%$-_";
60-
const size_t max_index = (sizeof(charset) - 1);
61-
return charset[ rand() % max_index ];
62-
};
63-
std::string str(length,0);
64-
std::generate_n( str.begin(), length, randchar );
65-
return str;
57+
thread_local static std::mt19937 rg{std::random_device{}()};
58+
thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2);
59+
60+
std::string s;
61+
62+
s.reserve(length);
63+
64+
while(length--)
65+
s += chrs[pick(rg)];
66+
67+
return s;
6668
}
6769

6870
//--------------------------------------------------------------

0 commit comments

Comments
 (0)