/* */ #include "SimpleRandomizer.h" #include #include #include #include #include "a2time.h" namespace aria2 { std::unique_ptr SimpleRandomizer::randomizer_; const std::unique_ptr& SimpleRandomizer::getInstance() { if(!randomizer_) { randomizer_.reset(new SimpleRandomizer()); } return randomizer_; } void SimpleRandomizer::init() { #ifndef __MINGW32__ srandom(time(0)^getpid()); #endif // !__MINGW32__ } SimpleRandomizer::SimpleRandomizer() { #ifdef __MINGW32__ BOOL r = CryptAcquireContext(&cryProvider_, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT|CRYPT_SILENT); assert(r); #endif // __MINGW32__ } 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(&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__ // TODO Warning: The maximum value of random() in some sytems (e.g., // Solaris and openbsd) is (2**31)-1. return RAND_MAX; #endif // !__MINGW32__ } long int SimpleRandomizer::getRandomNumber(long int to) { return getRandomNumber() % to; } long int SimpleRandomizer::operator()(long int to) { return getRandomNumber(to); } } // namespace aria2