Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
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// Qt-Security score:critical reason:cryptography
4
5#ifndef QRANDOM_H
6#define QRANDOM_H
7
8#include <QtCore/qalgorithms.h>
9#include <algorithm> // for std::generate
10#include <random> // for std::mt19937
11
12#ifdef min
13# undef min
14#endif
15#ifdef max
16# undef max
17#endif
18
19QT_BEGIN_NAMESPACE
20
21class QRandomGenerator
22{
23 // restrict the template parameters to unsigned integers 32 bits wide or larger
24 template <typename UInt> using IfValidUInt =
25 typename std::enable_if<std::is_unsigned<UInt>::value && sizeof(UInt) >= sizeof(uint), bool>::type;
26public:
27 QRandomGenerator(quint32 seedValue = 1)
28 : QRandomGenerator(&seedValue, 1)
29 {}
30 template <qsizetype N> QRandomGenerator(const quint32 (&seedBuffer)[N])
31 : QRandomGenerator(seedBuffer, seedBuffer + N)
32 {}
33 QRandomGenerator(const quint32 *seedBuffer, qsizetype len)
34 : QRandomGenerator(seedBuffer, seedBuffer + len)
35 {}
36 Q_CORE_EXPORT QRandomGenerator(std::seed_seq &sseq) noexcept;
37 Q_CORE_EXPORT QRandomGenerator(const quint32 *begin, const quint32 *end);
38
39 // copy constructor & assignment operator (move unnecessary)
40 Q_CORE_EXPORT QRandomGenerator(const QRandomGenerator &other);
41 Q_CORE_EXPORT QRandomGenerator &operator=(const QRandomGenerator &other);
42
43 ~QRandomGenerator() = default;
44
45 friend Q_CORE_EXPORT bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2);
46 friend bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
47 {
48 return !(rng1 == rng2);
49 }
50
51 quint32 generate()
52 {
53 return quint32(_fillRange(nullptr, 1));
54 }
55
56 quint64 generate64()
57 {
58 return _fillRange(nullptr, sizeof(quint64) / sizeof(quint32));
59 }
60
61 double generateDouble()
62 {
63 // IEEE 754 double precision has:
64 // 1 bit sign
65 // 10 bits exponent
66 // 53 bits mantissa
67 // In order for our result to be normalized in the range [0, 1), we
68 // need exactly 53 bits of random data. Use generate64() to get enough.
69 quint64 x = generate64();
70 quint64 limit = Q_UINT64_C(1) << std::numeric_limits<double>::digits;
71 x >>= std::numeric_limits<quint64>::digits - std::numeric_limits<double>::digits;
72 return double(x) / double(limit);
73 }
74
75 double bounded(double highest)
76 {
77 return generateDouble() * highest;
78 }
79
80 quint32 bounded(quint32 highest)
81 {
82 quint64 value = generate();
83 value *= highest;
84 value /= (max)() + quint64(1);
85 return quint32(value);
86 }
87
88 quint32 bounded(quint32 lowest, quint32 highest)
89 {
90 Q_ASSERT(highest > lowest);
91 return bounded(highest - lowest) + lowest;
92 }
93
94 int bounded(int highest)
95 {
96 Q_ASSERT(highest > 0);
97 return int(bounded(0U, quint32(highest)));
98 }
99
100 int bounded(int lowest, int highest)
101 {
102 return bounded(highest - lowest) + lowest;
103 }
104
105 quint64 bounded(quint64 highest);
106
107 quint64 bounded(quint64 lowest, quint64 highest)
108 {
109 Q_ASSERT(highest > lowest);
110 return bounded(highest - lowest) + lowest;
111 }
112
113 qint64 bounded(qint64 highest)
114 {
115 Q_ASSERT(highest > 0);
116 return qint64(bounded(quint64(0), quint64(highest)));
117 }
118
119 qint64 bounded(qint64 lowest, qint64 highest)
120 {
121 return bounded(highest - lowest) + lowest;
122 }
123
124 // these functions here only to help with ambiguous overloads
125 qint64 bounded(int lowest, qint64 highest)
126 {
127 return bounded(qint64(lowest), qint64(highest));
128 }
129 qint64 bounded(qint64 lowest, int highest)
130 {
131 return bounded(qint64(lowest), qint64(highest));
132 }
133
134 quint64 bounded(unsigned lowest, quint64 highest)
135 {
136 return bounded(quint64(lowest), quint64(highest));
137 }
138 quint64 bounded(quint64 lowest, unsigned highest)
139 {
140 return bounded(quint64(lowest), quint64(highest));
141 }
142
143 template <typename UInt, IfValidUInt<UInt> = true>
144 void fillRange(UInt *buffer, qsizetype count)
145 {
146 _fillRange(buffer, count * sizeof(UInt) / sizeof(quint32));
147 }
148
149 template <typename UInt, size_t N, IfValidUInt<UInt> = true>
150 void fillRange(UInt (&buffer)[N])
151 {
152 _fillRange(buffer, N * sizeof(UInt) / sizeof(quint32));
153 }
154
155 // API like std::seed_seq
156 template <typename ForwardIterator>
157 void generate(ForwardIterator begin, ForwardIterator end)
158 {
159 std::generate(begin, end, [this]() { return generate(); });
160 }
161
162 void generate(quint32 *begin, quint32 *end)
163 {
164 _fillRange(begin, end - begin);
165 }
166
167 // API like std:: random engines
168 typedef quint32 result_type;
169 result_type operator()() { return generate(); }
170 void seed(quint32 s = 1) { *this = { s }; }
171 void seed(std::seed_seq &sseq) noexcept { *this = { sseq }; }
172 Q_CORE_EXPORT void discard(unsigned long long z);
173 static constexpr result_type min() { return (std::numeric_limits<result_type>::min)(); }
174 static constexpr result_type max() { return (std::numeric_limits<result_type>::max)(); }
175
176 static inline Q_DECL_CONST_FUNCTION QRandomGenerator *system();
177 static inline Q_DECL_CONST_FUNCTION QRandomGenerator *global();
178 static inline QRandomGenerator securelySeeded();
179
180protected:
181 enum System {};
182 QRandomGenerator(System);
183
184private:
185 Q_CORE_EXPORT quint64 _fillRange(void *buffer, qptrdiff count);
186
187 struct InitialRandomData {
188 quintptr data[16 / sizeof(quintptr)];
189 };
190 friend InitialRandomData qt_initial_random_value() noexcept;
191 friend class QRandomGenerator64;
192 struct SystemGenerator;
193 struct SystemAndGlobalGenerators;
194 using RandomEngine = std::mersenne_twister_engine<quint32,
195 32,624,397,31,0x9908b0df,11,0xffffffff,7,0x9d2c5680,15,0xefc60000,18,1812433253>;
196
197 union Storage {
198 uint dummy;
199 RandomEngine twister;
200 RandomEngine &engine() { return twister; }
201 const RandomEngine &engine() const { return twister; }
202
203 static_assert(std::is_trivially_destructible<RandomEngine>::value,
204 "std::mersenne_twister not trivially destructible as expected");
205 constexpr Storage();
206 };
207 uint type;
208 Storage storage;
209};
210
211class QRandomGenerator64 : public QRandomGenerator
212{
213 QRandomGenerator64(System);
214public:
215 // unshadow generate() overloads, since we'll override.
216 using QRandomGenerator::generate;
217 quint64 generate() { return generate64(); }
218
220 result_type operator()() { return generate64(); }
221
222#ifndef Q_QDOC
223 QRandomGenerator64(quint32 seedValue = 1)
224 : QRandomGenerator(seedValue)
225 {}
226 template <qsizetype N> QRandomGenerator64(const quint32 (&seedBuffer)[N])
227 : QRandomGenerator(seedBuffer)
228 {}
229 QRandomGenerator64(const quint32 *seedBuffer, qsizetype len)
230 : QRandomGenerator(seedBuffer, len)
231 {}
232 QRandomGenerator64(std::seed_seq &sseq) noexcept
233 : QRandomGenerator(sseq)
234 {}
235 QRandomGenerator64(const quint32 *begin, const quint32 *end)
236 : QRandomGenerator(begin, end)
237 {}
238 QRandomGenerator64(const QRandomGenerator &other) : QRandomGenerator(other) {}
239
240 void discard(unsigned long long z)
241 {
242 Q_ASSERT_X(z * 2 > z, "QRandomGenerator64::discard",
243 "Overflow. Are you sure you want to skip over 9 quintillion samples?");
244 QRandomGenerator::discard(z * 2);
245 }
246
247 static constexpr result_type min() { return (std::numeric_limits<result_type>::min)(); }
248 static constexpr result_type max() { return (std::numeric_limits<result_type>::max)(); }
249 static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 *system();
250 static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 *global();
251 static Q_CORE_EXPORT QRandomGenerator64 securelySeeded();
252#endif // Q_QDOC
253};
254
255inline quint64 QRandomGenerator::bounded(quint64 highest)
256{
257 // Implement an algorithm similar to libc++'s uniform_int_distribution:
258 // loop around getting a random number, mask off any bits that "highest"
259 // will never need, then check if it's higher than "highest". The number of
260 // times the loop will run is unbounded but the probability of terminating
261 // is better than 1/2 on each iteration. Therefore, the average loop count
262 // should be less than 2.
263
264 const int width = qCountLeadingZeroBits(highest - 1);
265 const quint64 mask = (quint64(1) << (std::numeric_limits<quint64>::digits - width)) - 1;
266 quint64 v;
267 do {
268 v = generate64() & mask;
269 } while (v >= highest);
270 return v;
271}
272
273inline QRandomGenerator *QRandomGenerator::system()
274{
275 return QRandomGenerator64::system();
276}
277
278inline QRandomGenerator *QRandomGenerator::global()
279{
280 return QRandomGenerator64::global();
281}
282
283QRandomGenerator QRandomGenerator::securelySeeded()
284{
285 return QRandomGenerator64::securelySeeded();
286}
287
288QT_END_NAMESPACE
289
290#endif // QRANDOM_H
\inmodule QtCore
Definition qrandom.h:212
void discard(unsigned long long z)
Definition qrandom.h:240
result_type operator()()
Generates a 64-bit random quantity and returns it.
Definition qrandom.h:220
static constexpr result_type min()
Definition qrandom.h:247
quint64 result_type
A typedef to the type that operator() returns.
Definition qrandom.h:219
QRandomGenerator64(std::seed_seq &sseq) noexcept
Definition qrandom.h:232
QRandomGenerator64(const QRandomGenerator &other)
Definition qrandom.h:238
quint64 generate()
Generates one 64-bit random value and returns it.
Definition qrandom.h:217
QRandomGenerator64(quint32 seedValue=1)
Definition qrandom.h:223
QRandomGenerator64(const quint32 *begin, const quint32 *end)
Definition qrandom.h:235
QRandomGenerator64(const quint32 *seedBuffer, qsizetype len)
Definition qrandom.h:229
static constexpr result_type max()
Definition qrandom.h:248
QRandomGenerator64(const quint32(&seedBuffer)[N])
Definition qrandom.h:226
#define assert
QMutex QBasicMutex
Definition qmutex.h:360
static qsizetype callFillBuffer(FillBufferType f, T *v)
Definition qrandom.cpp:1268
static Q_NEVER_INLINE void fallback_fill(quint32 *ptr, qsizetype left) noexcept
Definition qrandom.cpp:210
static void fallback_update_seed(unsigned value)
Definition qrandom.cpp:198
bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
Definition qrandom.cpp:1221
#define Q_ASSERT(cond)
Definition qrandom.cpp:48
QRandomGenerator::InitialRandomData qt_initial_random_value() noexcept
Definition qrandom.cpp:1289
@ MersenneTwister
Definition qrandom_p.h:36
@ SystemRNG
Definition qrandom_p.h:35
@ UseSystemRNG
Definition qrandom_p.h:25
@ SkipSystemRNG
Definition qrandom_p.h:26
@ SetRandomData
Definition qrandom_p.h:28
@ SkipHWRNG
Definition qrandom_p.h:27
@ RandomDataMask
Definition qrandom_p.h:31
static QRandomGenerator64 * system()
Definition qrandom.cpp:353
static void securelySeed(QRandomGenerator *rng)
Definition qrandom.cpp:370
static SystemAndGlobalGenerators * self()
Definition qrandom.cpp:346
static QRandomGenerator64 * globalNoInit()
Definition qrandom.cpp:362
uchar data[sizeof(QRandomGenerator64)]
Definition qrandom.cpp:330
void generate(quint32 *begin, quint32 *end) noexcept(FillBufferNoexcept)
Definition qrandom.cpp:283
static SystemGenerator & self()
Definition qrandom.cpp:397
void generate(T *begin, T *end)
Definition qrandom.cpp:153