diff options
-rw-r--r-- | src/mongo/bson/oid.cpp | 22 | ||||
-rw-r--r-- | src/mongo/bson/oid.h | 7 | ||||
-rw-r--r-- | src/mongo/dbtests/jsobjtests.cpp | 16 |
3 files changed, 45 insertions, 0 deletions
diff --git a/src/mongo/bson/oid.cpp b/src/mongo/bson/oid.cpp index fb7d6ead891..4f25fef6085 100644 --- a/src/mongo/bson/oid.cpp +++ b/src/mongo/bson/oid.cpp @@ -19,6 +19,7 @@ #include <boost/functional/hash.hpp> +#include "mongo/platform/atomic_uint64.h" #include "mongo/bson/bsonobjbuilder.h" #include "mongo/bson/oid.h" #include "mongo/bson/util/atomic_int.h" @@ -135,6 +136,27 @@ namespace mongo { } } + void OID::initSequential() { + static AtomicUInt64 sequence; + + { + unsigned t = (unsigned) time(0); + unsigned char *T = (unsigned char *) &t; + _time[0] = T[3]; // big endian order because we use memcmp() to compare OID's + _time[1] = T[2]; + _time[2] = T[1]; + _time[3] = T[0]; + } + + { + unsigned long long nextNumber = sequence.fetchAndAdd(); + unsigned char* numberData = reinterpret_cast<unsigned char*>(&nextNumber); + for ( int i=0; i<8; i++ ) { + data[4+i] = numberData[7-i]; + } + } + } + void OID::init( string s ) { verify( s.size() == 24 ); const char *p = s.c_str(); diff --git a/src/mongo/bson/oid.h b/src/mongo/bson/oid.h index e803a290481..bd527f084ed 100644 --- a/src/mongo/bson/oid.h +++ b/src/mongo/bson/oid.h @@ -66,6 +66,13 @@ namespace mongo { /** sets the contents to a new oid / randomized value */ void init(); + /** sets the contents to a new oid + * guaranteed to be sequential + * NOT guaranteed to be globally unique + * only unique for this process + * */ + void initSequential(); + /** init from a 24 char hex string */ void init( std::string s ); diff --git a/src/mongo/dbtests/jsobjtests.cpp b/src/mongo/dbtests/jsobjtests.cpp index 8cb06099dca..b156f004621 100644 --- a/src/mongo/dbtests/jsobjtests.cpp +++ b/src/mongo/dbtests/jsobjtests.cpp @@ -1271,6 +1271,21 @@ namespace JsobjTests { ASSERT( BSON("" << max).woCompare( BSON("" << oid) )> 0 ); } }; + + class Seq { + public: + void run() { + for ( int i=0; i<10000; i++ ) { + OID a; + OID b; + + a.initSequential(); + b.initSequential(); + + ASSERT( a < b ); + } + } + }; } // namespace OIDTests @@ -2293,6 +2308,7 @@ namespace JsobjTests { add< OIDTests::increasing >(); add< OIDTests::ToDate >(); add< OIDTests::FromDate >(); + add< OIDTests::Seq >(); add< ValueStreamTests::LabelBasic >(); add< ValueStreamTests::LabelShares >(); add< ValueStreamTests::LabelDouble >(); |