libzypp
10.5.0
|
00001 00002 #include <cstdlib> 00003 #include <cstdio> 00004 #include <iostream> 00005 #include <fcntl.h> 00006 #include "zypp/base/Random.h" 00007 00008 using namespace std; 00009 00010 namespace zypp { namespace base { 00011 00012 // Taken from KApplication 00013 int random_int() 00014 { 00015 static bool init = false; 00016 if (!init) 00017 { 00018 unsigned int seed; 00019 init = true; 00020 int fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC); 00021 if (fd < 0 || ::read(fd, &seed, sizeof(seed)) != sizeof(seed)) 00022 { 00023 // No /dev/urandom... try something else. 00024 srand(getpid()); 00025 seed = rand()+time(0); 00026 } 00027 if (fd >= 0) close(fd); 00028 srand(seed); 00029 } 00030 return rand(); 00031 } 00032 00033 // Taken from KApplication 00034 std::string random_string(int length) 00035 { 00036 if (length <=0 ) return std::string(); 00037 00038 std::string str; str.resize( length ); 00039 int i = 0; 00040 while (length--) 00041 { 00042 int r=::random() % 62; 00043 r+=48; 00044 if (r>57) r+=7; 00045 if (r>90) r+=6; 00046 str[i++] = char(r); 00047 // so what if I work backwards? 00048 } 00049 return str; 00050 } 00051 00052 00053 } } 00054