1/****************************************************************************
2**
3** Copyright (C) 2017 Intel Corporation.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtCore module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#ifndef QRANDOM_H
41#define QRANDOM_H
42
43#include <QtCore/qglobal.h>
44#include <algorithm> // for std::generate
45#include <random> // for std::mt19937
46
47#ifdef min
48# undef min
49#endif
50#ifdef max
51# undef max
52#endif
53
54QT_BEGIN_NAMESPACE
55
56class QRandomGenerator
57{
58 // restrict the template parameters to unsigned integers 32 bits wide or larger
59 template <typename UInt> using IfValidUInt =
60 typename std::enable_if<std::is_unsigned<UInt>::value && sizeof(UInt) >= sizeof(uint), bool>::type;
61public:
62 QRandomGenerator(quint32 seedValue = 1)
63 : QRandomGenerator(&seedValue, 1)
64 {}
65 template <qsizetype N> QRandomGenerator(const quint32 (&seedBuffer)[N])
66 : QRandomGenerator(seedBuffer, seedBuffer + N)
67 {}
68 QRandomGenerator(const quint32 *seedBuffer, qsizetype len)
69 : QRandomGenerator(seedBuffer, seedBuffer + len)
70 {}
71 Q_CORE_EXPORT QRandomGenerator(std::seed_seq &sseq) Q_DECL_NOTHROW;
72 Q_CORE_EXPORT QRandomGenerator(const quint32 *begin, const quint32 *end);
73
74 // copy constructor & assignment operator (move unnecessary)
75 Q_CORE_EXPORT QRandomGenerator(const QRandomGenerator &other);
76 Q_CORE_EXPORT QRandomGenerator &operator=(const QRandomGenerator &other);
77
78 friend Q_CORE_EXPORT bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2);
79 friend bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
80 {
81 return !(rng1 == rng2);
82 }
83
84 quint32 generate()
85 {
86 quint32 ret;
87 fillRange(&ret, 1);
88 return ret;
89 }
90
91 quint64 generate64()
92 {
93 quint32 buf[2];
94 fillRange(buf);
95 return buf[0] | (quint64(buf[1]) << 32);
96 }
97
98 double generateDouble()
99 {
100 // IEEE 754 double precision has:
101 // 1 bit sign
102 // 10 bits exponent
103 // 53 bits mantissa
104 // In order for our result to be normalized in the range [0, 1), we
105 // need exactly 53 bits of random data. Use generate64() to get enough.
106 quint64 x = generate64();
107 quint64 limit = Q_UINT64_C(1) << std::numeric_limits<double>::digits;
108 x >>= std::numeric_limits<quint64>::digits - std::numeric_limits<double>::digits;
109 return double(x) / double(limit);
110 }
111
112 double bounded(double highest)
113 {
114 return generateDouble() * highest;
115 }
116
117 quint32 bounded(quint32 highest)
118 {
119 quint64 value = generate();
120 value *= highest;
121 value /= (max)() + quint64(1);
122 return quint32(value);
123 }
124
125 int bounded(int highest)
126 {
127 return int(bounded(quint32(highest)));
128 }
129
130 quint32 bounded(quint32 lowest, quint32 highest)
131 {
132 return bounded(highest - lowest) + lowest;
133 }
134
135 int bounded(int lowest, int highest)
136 {
137 return bounded(highest - lowest) + lowest;
138 }
139
140 template <typename UInt, IfValidUInt<UInt> = true>
141 void fillRange(UInt *buffer, qsizetype count)
142 {
143 _fillRange(buffer, buffer + count);
144 }
145
146 template <typename UInt, size_t N, IfValidUInt<UInt> = true>
147 void fillRange(UInt (&buffer)[N])
148 {
149 _fillRange(buffer, buffer + N);
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
159 void generate(quint32 *begin, quint32 *end)
160 {
161 _fillRange(begin, end);
162 }
163
164 // API like std:: random engines
165 typedef quint32 result_type;
166 result_type operator()() { return generate(); }
167 void seed(quint32 s = 1) { *this = { s }; }
168 void seed(std::seed_seq &sseq) Q_DECL_NOTHROW { *this = { sseq }; }
169 Q_CORE_EXPORT void discard(unsigned long long z);
170 static Q_DECL_CONSTEXPR result_type min() { return std::numeric_limits<result_type>::min(); }
171 static Q_DECL_CONSTEXPR result_type max() { return std::numeric_limits<result_type>::max(); }
172
173 static inline Q_DECL_CONST_FUNCTION QRandomGenerator *system();
174 static inline Q_DECL_CONST_FUNCTION QRandomGenerator *global();
175 static inline QRandomGenerator securelySeeded();
176
177protected:
178 enum System {};
179 QRandomGenerator(System);
180
181private:
182 Q_CORE_EXPORT void _fillRange(void *buffer, void *bufferEnd);
183
184 friend class QRandomGenerator64;
185 struct SystemGenerator;
186 struct SystemAndGlobalGenerators;
187 using RandomEngine = std::mersenne_twister_engine<quint32,
188 32,624,397,31,0x9908b0df,11,0xffffffff,7,0x9d2c5680,15,0xefc60000,18,1812433253>;
189
190 union Storage {
191 uint dummy;
192#ifdef Q_COMPILER_UNRESTRICTED_UNIONS
193 RandomEngine twister;
194 RandomEngine &engine() { return twister; }
195 const RandomEngine &engine() const { return twister; }
196#else
197 std::aligned_storage<sizeof(RandomEngine), Q_ALIGNOF(RandomEngine)>::type buffer;
198 RandomEngine &engine() { return reinterpret_cast<RandomEngine &>(buffer); }
199 const RandomEngine &engine() const { return reinterpret_cast<const RandomEngine &>(buffer); }
200#endif
201
202 Q_STATIC_ASSERT_X(std::is_trivially_destructible<RandomEngine>::value,
203 "std::mersenne_twister not trivially destructible as expected");
204 Q_DECL_CONSTEXPR Storage();
205 };
206 uint type;
207 Storage storage;
208};
209
210class QRandomGenerator64 : public QRandomGenerator
211{
212 QRandomGenerator64(System);
213public:
214 // unshadow generate() overloads, since we'll override.
215 using QRandomGenerator::generate;
216 quint64 generate() { return generate64(); }
217
218 typedef quint64 result_type;
219 result_type operator()() { return generate64(); }
220
221#ifndef Q_QDOC
222 QRandomGenerator64(quint32 seedValue = 1)
223 : QRandomGenerator(seedValue)
224 {}
225 template <qsizetype N> QRandomGenerator64(const quint32 (&seedBuffer)[N])
226 : QRandomGenerator(seedBuffer)
227 {}
228 QRandomGenerator64(const quint32 *seedBuffer, qsizetype len)
229 : QRandomGenerator(seedBuffer, len)
230 {}
231 QRandomGenerator64(std::seed_seq &sseq) Q_DECL_NOTHROW
232 : QRandomGenerator(sseq)
233 {}
234 QRandomGenerator64(const quint32 *begin, const quint32 *end)
235 : QRandomGenerator(begin, end)
236 {}
237 QRandomGenerator64(const QRandomGenerator &other) : QRandomGenerator(other) {}
238
239 void discard(unsigned long long z)
240 {
241 Q_ASSERT_X(z * 2 > z, "QRandomGenerator64::discard",
242 "Overflow. Are you sure you want to skip over 9 quintillion samples?");
243 QRandomGenerator::discard(z * 2);
244 }
245
246 static Q_DECL_CONSTEXPR result_type min() { return std::numeric_limits<result_type>::min(); }
247 static Q_DECL_CONSTEXPR result_type max() { return std::numeric_limits<result_type>::max(); }
248 static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 *system();
249 static Q_DECL_CONST_FUNCTION Q_CORE_EXPORT QRandomGenerator64 *global();
250 static Q_CORE_EXPORT QRandomGenerator64 securelySeeded();
251#endif // Q_QDOC
252};
253
254inline QRandomGenerator *QRandomGenerator::system()
255{
256 return QRandomGenerator64::system();
257}
258
259inline QRandomGenerator *QRandomGenerator::global()
260{
261 return QRandomGenerator64::global();
262}
263
264QRandomGenerator QRandomGenerator::securelySeeded()
265{
266 return QRandomGenerator64::securelySeeded();
267}
268
269QT_END_NAMESPACE
270
271#endif // QRANDOM_H
272