Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
qrandom.h
Go to the documentation of this file.
1// Copyright (C) 2020 Intel Corporation.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#ifndef QRANDOM_H
5#define QRANDOM_H
6
7#include <QtCore/qalgorithms.h>
8#include <algorithm> // for std::generate
9#include <random> // for std::mt19937
10
11#ifdef min
12# undef min
13#endif
14#ifdef max
15# undef max
16#endif
17
19
21{
22 // restrict the template parameters to unsigned integers 32 bits wide or larger
23 template <typename UInt> using IfValidUInt =
24 typename std::enable_if<std::is_unsigned<UInt>::value && sizeof(UInt) >= sizeof(uint), bool>::type;
25public:
27 : QRandomGenerator(&seedValue, 1)
28 {}
29 template <qsizetype N> QRandomGenerator(const quint32 (&seedBuffer)[N])
30 : QRandomGenerator(seedBuffer, seedBuffer + N)
31 {}
33 : QRandomGenerator(seedBuffer, seedBuffer + len)
34 {}
35 Q_CORE_EXPORT QRandomGenerator(std::seed_seq &sseq) noexcept;
36 Q_CORE_EXPORT QRandomGenerator(const quint32 *begin, const quint32 *end);
37
38 // copy constructor & assignment operator (move unnecessary)
39 Q_CORE_EXPORT QRandomGenerator(const QRandomGenerator &other);
40 Q_CORE_EXPORT QRandomGenerator &operator=(const QRandomGenerator &other);
41
42 friend Q_CORE_EXPORT bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2);
43 friend bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
44 {
45 return !(rng1 == rng2);
46 }
47
49 {
50 return quint32(_fillRange(nullptr, 1));
51 }
52
54 {
55 return _fillRange(nullptr, sizeof(quint64) / sizeof(quint32));
56 }
57
59 {
60 // IEEE 754 double precision has:
61 // 1 bit sign
62 // 10 bits exponent
63 // 53 bits mantissa
64 // In order for our result to be normalized in the range [0, 1), we
65 // need exactly 53 bits of random data. Use generate64() to get enough.
67 quint64 limit = Q_UINT64_C(1) << std::numeric_limits<double>::digits;
68 x >>= std::numeric_limits<quint64>::digits - std::numeric_limits<double>::digits;
69 return double(x) / double(limit);
70 }
71
72 double bounded(double highest)
73 {
74 return generateDouble() * highest;
75 }
76
78 {
80 value *= highest;
81 value /= (max)() + quint64(1);
82 return quint32(value);
83 }
84
85 quint32 bounded(quint32 lowest, quint32 highest)
86 {
87 Q_ASSERT(highest > lowest);
88 return bounded(highest - lowest) + lowest;
89 }
90
91 int bounded(int highest)
92 {
93 Q_ASSERT(highest > 0);
94 return int(bounded(0U, quint32(highest)));
95 }
96
97 int bounded(int lowest, int highest)
98 {
99 return bounded(highest - lowest) + lowest;
100 }
101
102 quint64 bounded(quint64 highest);
103
105 {
106 Q_ASSERT(highest > lowest);
107 return bounded(highest - lowest) + lowest;
108 }
109
111 {
112 Q_ASSERT(highest > 0);
113 return qint64(bounded(quint64(0), quint64(highest)));
114 }
115
116 qint64 bounded(qint64 lowest, qint64 highest)
117 {
118 return bounded(highest - lowest) + lowest;
119 }
120
121 // these functions here only to help with ambiguous overloads
122 qint64 bounded(int lowest, qint64 highest)
123 {
124 return bounded(qint64(lowest), qint64(highest));
125 }
126 qint64 bounded(qint64 lowest, int highest)
127 {
128 return bounded(qint64(lowest), qint64(highest));
129 }
130
131 quint64 bounded(unsigned lowest, quint64 highest)
132 {
133 return bounded(quint64(lowest), quint64(highest));
134 }
135 quint64 bounded(quint64 lowest, unsigned highest)
136 {
137 return bounded(quint64(lowest), quint64(highest));
138 }
139
140 template <typename UInt, IfValidUInt<UInt> = true>
142 {
143 _fillRange(buffer, count * sizeof(UInt) / sizeof(quint32));
144 }
145
146 template <typename UInt, size_t N, IfValidUInt<UInt> = true>
147 void fillRange(UInt (&buffer)[N])
148 {
149 _fillRange(buffer, N * sizeof(UInt) / sizeof(quint32));
150 }
151
152 // API like std::seed_seq
153 template <typename ForwardIterator>
154 void generate(ForwardIterator begin, ForwardIterator end)
155 {
156 std::generate(begin, end, [this]() { return generate(); });
157 }
158
160 {
161 _fillRange(begin, end - begin);
162 }
163
164 // API like std:: random engines
167 void seed(quint32 s = 1) { *this = { s }; }
168 void seed(std::seed_seq &sseq) noexcept { *this = { sseq }; }
169 Q_CORE_EXPORT void discard(unsigned long long z);
170 static constexpr result_type min() { return (std::numeric_limits<result_type>::min)(); }
171 static constexpr result_type max() { return (std::numeric_limits<result_type>::max)(); }
172
175 static inline QRandomGenerator securelySeeded();
176
177protected:
178 enum System {};
180
181private:
182 Q_CORE_EXPORT quint64 _fillRange(void *buffer, qptrdiff count);
183
184 struct InitialRandomData {
185 quintptr data[16 / sizeof(quintptr)];
186 };
187 friend InitialRandomData qt_initial_random_value() noexcept;
188 friend class QRandomGenerator64;
189 struct SystemGenerator;
191 using RandomEngine = std::mersenne_twister_engine<quint32,
192 32,624,397,31,0x9908b0df,11,0xffffffff,7,0x9d2c5680,15,0xefc60000,18,1812433253>;
193
194 union Storage {
195 uint dummy;
196 RandomEngine twister;
197 RandomEngine &engine() { return twister; }
198 const RandomEngine &engine() const { return twister; }
199
200 static_assert(std::is_trivially_destructible<RandomEngine>::value,
201 "std::mersenne_twister not trivially destructible as expected");
202 constexpr Storage();
203 };
204 uint type;
205 Storage storage;
206};
207
209{
211public:
212 // unshadow generate() overloads, since we'll override.
215
218
219#ifndef Q_QDOC
221 : QRandomGenerator(seedValue)
222 {}
223 template <qsizetype N> QRandomGenerator64(const quint32 (&seedBuffer)[N])
224 : QRandomGenerator(seedBuffer)
225 {}
227 : QRandomGenerator(seedBuffer, len)
228 {}
229 QRandomGenerator64(std::seed_seq &sseq) noexcept
231 {}
236
237 void discard(unsigned long long z)
238 {
239 Q_ASSERT_X(z * 2 > z, "QRandomGenerator64::discard",
240 "Overflow. Are you sure you want to skip over 9 quintillion samples?");
242 }
243
244 static constexpr result_type min() { return (std::numeric_limits<result_type>::min)(); }
245 static constexpr result_type max() { return (std::numeric_limits<result_type>::max)(); }
246 static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 *system();
247 static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 *global();
248 static Q_CORE_EXPORT QRandomGenerator64 securelySeeded();
249#endif // Q_QDOC
250};
251
253{
254 // Implement an algorithm similar to libc++'s uniform_int_distribution:
255 // loop around getting a random number, mask off any bits that "highest"
256 // will never need, then check if it's higher than "highest". The number of
257 // times the loop will run is unbounded but the probability of terminating
258 // is better than 1/2 on each iteration. Therefore, the average loop count
259 // should be less than 2.
260
261 const int width = qCountLeadingZeroBits(highest - 1);
262 const quint64 mask = (quint64(1) << (std::numeric_limits<quint64>::digits - width)) - 1;
263 quint64 v;
264 do {
265 v = generate64() & mask;
266 } while (v >= highest);
267 return v;
268}
269
274
279
284
286
287#endif // QRANDOM_H
\inmodule QtCore
Definition qrandom.h:209
void discard(unsigned long long z)
Definition qrandom.h:237
static Q_CORE_EXPORT QRandomGenerator64 securelySeeded()
Definition qrandom.cpp:1152
result_type operator()()
Generates a 64-bit random quantity and returns it.
Definition qrandom.h:217
static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 * global()
Definition qrandom.cpp:1134
static constexpr result_type min()
Definition qrandom.h:244
QRandomGenerator64(std::seed_seq &sseq) noexcept
Definition qrandom.h:229
quint64 result_type
A typedef to the type that operator() returns.
Definition qrandom.h:216
QRandomGenerator64(const QRandomGenerator &other)
Definition qrandom.h:235
quint64 generate()
Generates one 64-bit random value and returns it.
Definition qrandom.h:214
QRandomGenerator64(quint32 seedValue=1)
Definition qrandom.h:220
QRandomGenerator64(const quint32 *begin, const quint32 *end)
Definition qrandom.h:232
QRandomGenerator64(const quint32 *seedBuffer, qsizetype len)
Definition qrandom.h:226
static constexpr result_type max()
Definition qrandom.h:245
QRandomGenerator64(const quint32(&seedBuffer)[N])
Definition qrandom.h:223
static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 * system()
Definition qrandom.cpp:1127
\inmodule QtCore \reentrant
Definition qrandom.h:21
friend InitialRandomData qt_initial_random_value() noexcept
Definition qrandom.cpp:1288
friend class QRandomGenerator64
Definition qrandom.h:188
static Q_DECL_CONST_FUNCTION QRandomGenerator * system()
\threadsafe
Definition qrandom.h:270
Q_CORE_EXPORT QRandomGenerator & operator=(const QRandomGenerator &other)
Definition qrandom.cpp:1180
qint64 bounded(qint64 highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:110
double generateDouble()
Generates one random qreal in the canonical range [0, 1) (that is, inclusive of zero and exclusive of...
Definition qrandom.h:58
quint64 bounded(quint64 lowest, unsigned highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:135
Q_CORE_EXPORT void discard(unsigned long long z)
Discards the next z entries from the sequence.
Definition qrandom.cpp:1211
QRandomGenerator(quint32 seedValue=1)
Initializes this QRandomGenerator object with the value seedValue as the seed.
Definition qrandom.h:26
void generate(quint32 *begin, quint32 *end)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:159
QRandomGenerator(const quint32 *seedBuffer, qsizetype len)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:32
quint32 generate()
Generates a 32-bit random quantity and returns it.
Definition qrandom.h:48
static Q_DECL_CONST_FUNCTION QRandomGenerator * global()
\threadsafe
Definition qrandom.h:275
void fillRange(UInt(&buffer)[N])
Generates N 32- or 64-bit quantities (depending on the type UInt) and stores them in the buffer array...
Definition qrandom.h:147
int bounded(int highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:91
quint64 generate64()
Generates a 64-bit random quantity and returns it.
Definition qrandom.h:53
static constexpr result_type max()
Returns the maximum value that QRandomGenerator may ever generate.
Definition qrandom.h:171
qint64 bounded(int lowest, qint64 highest)
Definition qrandom.h:122
double bounded(double highest)
Generates one random double in the range between 0 (inclusive) and highest (exclusive).
Definition qrandom.h:72
quint64 bounded(quint64 lowest, quint64 highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:104
quint32 result_type
A typedef to the type that operator() returns.
Definition qrandom.h:165
friend Q_CORE_EXPORT bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
Returns true if the two engines rng1 and rng2 are at the same state or if they are both reading from ...
Definition qrandom.cpp:1220
void generate(ForwardIterator begin, ForwardIterator end)
Generates 32-bit quantities and stores them in the range between begin and end.
Definition qrandom.h:154
quint32 bounded(quint32 lowest, quint32 highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:85
void seed(std::seed_seq &sseq) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:168
static constexpr result_type min()
Returns the minimum value that QRandomGenerator may ever generate.
Definition qrandom.h:170
qint64 bounded(qint64 lowest, qint64 highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:116
quint32 bounded(quint32 highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:77
friend bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
Returns true if the two engines rng1 and rng2 are at different states or if one of them is reading fr...
Definition qrandom.h:43
QRandomGenerator(const quint32(&seedBuffer)[N])
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:29
quint64 bounded(unsigned lowest, quint64 highest)
Definition qrandom.h:131
static QRandomGenerator securelySeeded()
Returns a new QRandomGenerator object that was securely seeded with QRandomGenerator::system().
Definition qrandom.h:280
result_type operator()()
Generates a 32-bit random quantity and returns it.
Definition qrandom.h:166
qint64 bounded(qint64 lowest, int highest)
Definition qrandom.h:126
int bounded(int lowest, int highest)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrandom.h:97
void fillRange(UInt *buffer, qsizetype count)
Generates count 32- or 64-bit quantities (depending on the type UInt) and stores them in the buffer p...
Definition qrandom.h:141
void seed(quint32 s=1)
Reseeds this object using the value seed as the seed.
Definition qrandom.h:167
Combined button and popup list for selecting options.
QT_POPCOUNT_RELAXED_CONSTEXPR uint qCountLeadingZeroBits(quint32 v) noexcept
#define Q_DECL_CONST_FUNCTION
EGLOutputLayerEXT EGLint EGLAttrib value
[5]
GLsizei const GLfloat * v
[13]
GLuint GLfloat GLfloat GLfloat GLfloat GLfloat z
GLint GLint GLint GLint GLint x
[0]
GLuint GLuint end
GLenum GLenum GLsizei count
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
GLenum GLuint buffer
GLint GLsizei width
GLenum type
GLint GLint GLint GLint GLint GLint GLint GLbitfield mask
GLdouble s
[6]
Definition qopenglext.h:235
GLint limit
GLenum GLsizei len
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
#define Q_ASSERT_X(cond, x, msg)
Definition qrandom.cpp:48
QtPrivate::QRegularExpressionMatchIteratorRangeBasedForIterator begin(const QRegularExpressionMatchIterator &iterator)
#define Q_UINT64_C(c)
Definition qtypes.h:58
unsigned int quint32
Definition qtypes.h:50
size_t quintptr
Definition qtypes.h:167
ptrdiff_t qptrdiff
Definition qtypes.h:164
unsigned long long quint64
Definition qtypes.h:61
ptrdiff_t qsizetype
Definition qtypes.h:165
unsigned int uint
Definition qtypes.h:34
long long qint64
Definition qtypes.h:60
std::seed_seq sseq(seedBuffer, seedBuffer+len)
[3]
QSharedPointer< T > other(t)
[5]
QJSEngine engine
[0]