3
/* Copyright 2012 10gen Inc.
5
* Licensed under the Apache License, Version 2.0 (the "License");
6
* you may not use this file except in compliance with the License.
7
* You may obtain a copy of the License at
9
* http://www.apache.org/licenses/LICENSE-2.0
11
* Unless required by applicable law or agreed to in writing, software
12
* distributed under the License is distributed on an "AS IS" BASIS,
13
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
* See the License for the specific language governing permissions and
15
* limitations under the License.
18
#include "mongo/platform/random.h"
32
#include "mongo/platform/basic.h"
36
// ---- PseudoRandom -----
38
int32_t PseudoRandom::nextInt32() {
39
int32_t t = _x ^ (_x << 11);
43
return _w = _w ^ (_w >> 19) ^ (t ^ (t >> 8));
47
const int32_t default_y = 362436069;
48
const int32_t default_z = 521288629;
49
const int32_t default_w = 88675123;
52
PseudoRandom::PseudoRandom( int32_t seed ) {
60
PseudoRandom::PseudoRandom( uint32_t seed ) {
61
_x = static_cast<int32_t>(seed);
68
PseudoRandom::PseudoRandom( int64_t seed ) {
69
int32_t high = seed >> 32;
70
int32_t low = seed & 0xFFFFFFFF;
78
int64_t PseudoRandom::nextInt64() {
79
int64_t a = nextInt32();
80
int64_t b = nextInt32();
81
return ( a << 32 ) | b;
84
// --- SecureRandom ----
86
SecureRandom::~SecureRandom() {
90
class WinSecureRandom : public SecureRandom {
91
virtual ~WinSecureRandom(){}
100
return ( static_cast<int64_t>(a) << 32 ) | b;
104
SecureRandom* SecureRandom::create() {
105
return new WinSecureRandom();
108
#elif defined(__linux__) || defined(__sunos__) || defined(__APPLE__) || defined(__FreeBSD_kernel__)
110
class InputStreamSecureRandom : public SecureRandom {
112
InputStreamSecureRandom( const char* fn ) {
113
_in = new std::ifstream( fn, std::ios::binary | std::ios::in );
114
if ( !_in->is_open() ) {
115
std::cerr << "can't open " << fn << " " << strerror(errno) << std::endl;
120
~InputStreamSecureRandom() {
124
int64_t nextInt64() {
126
_in->read( reinterpret_cast<char*>( &r ), sizeof(r) );
137
SecureRandom* SecureRandom::create() {
138
return new InputStreamSecureRandom( "/dev/urandom" );
142
class SRandSecureRandom : public SecureRandom {
144
SRandSecureRandom() {
148
int64_t nextInt64() {
152
return ( static_cast<int64_t>(a) << 32 ) | b;
156
SecureRandom* SecureRandom::create() {
157
return new SRandSecureRandom();