summaryrefslogtreecommitdiff
path: root/src/SimpleRandomizer.cc
diff options
context:
space:
mode:
authorTatsuhiro Tsujikawa <tatsuhiro.t@gmail.com>2011-08-18 18:03:06 +0900
committerTatsuhiro Tsujikawa <tatsuhiro.t@gmail.com>2011-08-18 18:03:06 +0900
commitbf42505b7b32400bfdc183fb5f1588394e6417dc (patch)
tree43b6019dded6085cf4e4e1170d9540d2f76e4874 /src/SimpleRandomizer.cc
parentdce0667c0be31a8dbaee3f6ec7e223d11ec9f7dd (diff)
MinGW32: Use CryptGenRandom() to generate random number.
MinGW32 lacks random(), so we use CryptGenRandom() as a replacement. In the implementation, SimpleRandomizer::getRandomNumber() returns the random number in range [0, INT32_MAX]. Thus, simpleRandomizer::getMaxRandomNumber() returns INT32_MAX.
Diffstat (limited to 'src/SimpleRandomizer.cc')
-rw-r--r--src/SimpleRandomizer.cc40
1 files changed, 37 insertions, 3 deletions
diff --git a/src/SimpleRandomizer.cc b/src/SimpleRandomizer.cc
index 53111db6..48a46b96 100644
--- a/src/SimpleRandomizer.cc
+++ b/src/SimpleRandomizer.cc
@@ -33,11 +33,13 @@
*/
/* copyright --> */
#include "SimpleRandomizer.h"
-#include "a2time.h"
+
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>
+#include "a2time.h"
+
namespace aria2 {
SharedHandle<SimpleRandomizer> SimpleRandomizer::randomizer_;
@@ -52,25 +54,57 @@ const SharedHandle<SimpleRandomizer>& SimpleRandomizer::getInstance()
void SimpleRandomizer::init()
{
+#ifndef __MINGW32__
srandom(time(0)^getpid());
+#endif // !__MINGW32__
}
-SimpleRandomizer::SimpleRandomizer() {}
+SimpleRandomizer::SimpleRandomizer()
+{
+#ifdef __MINGW32__
+ BOOL r = CryptAcquireContext(&cryProvider_, 0, 0, PROV_RSA_FULL,
+ CRYPT_VERIFYCONTEXT|CRYPT_SILENT);
+ assert(r);
+#endif // __MINGW32__
+}
-SimpleRandomizer::~SimpleRandomizer() {}
+SimpleRandomizer::~SimpleRandomizer()
+{
+#ifdef __MINGW32__
+ CryptReleaseContext(cryProvider_, 0);
+#endif // __MINGW32__
+}
long int SimpleRandomizer::getRandomNumber()
{
+#ifdef __MINGW32__
+ int32_t val;
+ BOOL r = CryptGenRandom(cryProvider_, sizeof(val),
+ reinterpret_cast<BYTE*>(&val));
+ assert(r);
+ if(val == INT32_MIN) {
+ val = INT32_MAX;
+ } else if(val < 0) {
+ val = -val;
+ }
+ return val;
+#else // !__MINGW32__
return random();
+#endif // !__MINGW32__
}
long int SimpleRandomizer::getMaxRandomNumber()
{
+#ifdef __MINGW32__
+ return INT32_MAX;
+#else // !__MINGW32__
return RAND_MAX;
+#endif // !__MINGW32__
}
long int SimpleRandomizer::getRandomNumber(long int to)
{
+
return(long int)(((double)to)*getRandomNumber()/(getMaxRandomNumber()+1.0));
}