1 // Boost random_generator.hpp header file ----------------------------------------------//
3 // Copyright 2010 Andy Tompkins.
4 // Distributed under the Boost Software License, Version 1.0. (See
5 // accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt)
8 #ifndef BOOST_UUID_RANDOM_GENERATOR_HPP
9 #define BOOST_UUID_RANDOM_GENERATOR_HPP
11 #include <boost/uuid/uuid.hpp>
12 #include <boost/uuid/detail/seed_rng.hpp>
13 #include <boost/random/uniform_int.hpp>
14 #include <boost/random/variate_generator.hpp>
15 #include <boost/random/mersenne_twister.hpp>
16 #include <boost/core/null_deleter.hpp>
17 #include <boost/assert.hpp>
18 #include <boost/shared_ptr.hpp>
24 // generate a random-based uuid
25 template <typename UniformRandomNumberGenerator>
26 class basic_random_generator {
28 typedef uniform_int<unsigned long> distribution_type;
29 typedef variate_generator<UniformRandomNumberGenerator*, distribution_type> generator_type;
32 typedef uuid result_type;
34 // default constructor creates the random number generator
35 basic_random_generator()
36 : pURNG(new UniformRandomNumberGenerator)
40 ( (std::numeric_limits<unsigned long>::min)()
41 , (std::numeric_limits<unsigned long>::max)()
45 // seed the random number generator
49 // keep a reference to a random number generator
50 // don't seed a given random number generator
51 explicit basic_random_generator(UniformRandomNumberGenerator& gen)
52 : pURNG(&gen, boost::null_deleter())
56 ( (std::numeric_limits<unsigned long>::min)()
57 , (std::numeric_limits<unsigned long>::max)()
62 // keep a pointer to a random number generator
63 // don't seed a given random number generator
64 explicit basic_random_generator(UniformRandomNumberGenerator* pGen)
65 : pURNG(pGen, boost::null_deleter())
69 ( (std::numeric_limits<unsigned long>::min)()
70 , (std::numeric_limits<unsigned long>::max)()
82 unsigned long random_value = generator();
83 for (uuid::iterator it=u.begin(); it!=u.end(); ++it, ++i) {
84 if (i==sizeof(unsigned long)) {
85 random_value = generator();
89 // static_cast gets rid of warnings of converting unsigned long to boost::uint8_t
90 *it = static_cast<uuid::value_type>((random_value >> (i*8)) & 0xFF);
95 *(u.begin()+8) &= 0xBF;
96 *(u.begin()+8) |= 0x80;
100 *(u.begin()+6) &= 0x4F; //0b01001111
101 *(u.begin()+6) |= 0x40; //0b01000000
107 shared_ptr<UniformRandomNumberGenerator> pURNG;
108 generator_type generator;
111 typedef basic_random_generator<mt19937> random_generator;
113 }} // namespace boost::uuids
115 #endif //BOOST_UUID_RANDOM_GENERATOR_HPP