summaryrefslogtreecommitdiff
path: root/src/mongo/platform
diff options
context:
space:
mode:
authorEliot Horowitz <eliot@10gen.com>2012-11-13 10:13:25 -0500
committerEliot Horowitz <eliot@10gen.com>2012-11-13 17:35:46 -0500
commit68a2023506a217e787e0cb50d7de60b36d4fa17f (patch)
tree7877ba21503746a3f76d06245b3f2815e4a1de8f /src/mongo/platform
parent93fdafcb4c4883d401a0726b67f2141404daa9ee (diff)
downloadmongo-68a2023506a217e787e0cb50d7de60b36d4fa17f.tar.gz
some Random tests and helpers
Diffstat (limited to 'src/mongo/platform')
-rw-r--r--src/mongo/platform/random.cpp9
-rw-r--r--src/mongo/platform/random.h9
-rw-r--r--src/mongo/platform/random_test.cpp31
3 files changed, 45 insertions, 4 deletions
diff --git a/src/mongo/platform/random.cpp b/src/mongo/platform/random.cpp
index 97bde99da4a..fabb4bf69b4 100644
--- a/src/mongo/platform/random.cpp
+++ b/src/mongo/platform/random.cpp
@@ -48,6 +48,15 @@ namespace mongo {
return rand_r( &_seed );
}
#endif
+ PseudoRandom::PseudoRandom( int64_t seed ) {
+ _seed = static_cast<uint32_t>( seed );
+ }
+
+ int64_t PseudoRandom::nextInt64() {
+ int64_t a = nextInt32();
+ int64_t b = nextInt32();
+ return ( a << 32 ) | b;
+ }
// --- SecureRandom ----
diff --git a/src/mongo/platform/random.h b/src/mongo/platform/random.h
index 38ba7684fee..fc11b725eb4 100644
--- a/src/mongo/platform/random.h
+++ b/src/mongo/platform/random.h
@@ -21,21 +21,22 @@
namespace mongo {
+ // TODO, make this is generate 64-bit numbers
class PseudoRandom {
public:
- PseudoRandom( unsigned seed )
- : _seed( seed ) {
- }
+ PseudoRandom( int64_t seed );
int32_t nextInt32();
+ int64_t nextInt64();
+
/**
* @return a number between 0 and max
*/
int32_t nextInt32( int32_t max ) { return nextInt32() % max; }
private:
- unsigned _seed;
+ uint32_t _seed;
};
/**
diff --git a/src/mongo/platform/random_test.cpp b/src/mongo/platform/random_test.cpp
index 0752604c5ca..c8a5444638f 100644
--- a/src/mongo/platform/random_test.cpp
+++ b/src/mongo/platform/random_test.cpp
@@ -16,11 +16,14 @@
* limitations under the License.
*/
+#include <set>
+
#include "mongo/platform/random.h"
#include "mongo/unittest/unittest.h"
namespace mongo {
+
TEST( RandomTest, Seed1 ) {
#ifndef _WIN32
PseudoRandom a( 12 );
@@ -32,6 +35,34 @@ namespace mongo {
#endif
}
+ TEST( RandomTest, Seed2 ) {
+ PseudoRandom a( 12 );
+ PseudoRandom b( 12 );
+
+ for ( int i = 0; i < 100; i++ ) {
+ ASSERT_EQUALS( a.nextInt64(), b.nextInt64() );
+ }
+ }
+
+ TEST( RandomTest, R1 ) {
+ PseudoRandom a( 11 );
+ std::set<int32_t> s;
+ for ( int i = 0; i < 100; i++ ) {
+ s.insert( a.nextInt32() );
+ }
+ ASSERT_EQUALS( 100U, s.size() );
+ }
+
+ TEST( RandomTest, R2 ) {
+ PseudoRandom a( 11 );
+ std::set<int64_t> s;
+ for ( int i = 0; i < 100; i++ ) {
+ s.insert( a.nextInt64() );
+ }
+ ASSERT_EQUALS( 100U, s.size() );
+ }
+
+
TEST( RandomTest, Secure1 ) {
SecureRandom* a = SecureRandom::create();
SecureRandom* b = SecureRandom::create();