summaryrefslogtreecommitdiffstats
path: root/tests/auto/corelib/global/qrandomgenerator/tst_qrandomgenerator.cpp
blob: d1c0c8e9652e71fe54232b03e897932e62474a20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/****************************************************************************
**
** Copyright (C) 2017 Intel Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest>
#include <qlinkedlist.h>
#include <qobject.h>
#include <qrandom.h>
#include <qvector.h>
#include <private/qrandom_p.h>

#include <algorithm>
#include <random>

#if !QT_CONFIG(getentropy) && (defined(Q_OS_BSD4) || defined(Q_OS_WIN))
#  define HAVE_FALLBACK_ENGINE
#endif

#define COMMA   ,
#define QVERIFY_3TIMES(statement)    \
    do {\
        if (!QTest::qVerify(static_cast<bool>(statement), #statement, "1st try", __FILE__, __LINE__))\
            if (!QTest::qVerify(static_cast<bool>(statement), #statement, "2nd try", __FILE__, __LINE__))\
                if (!QTest::qVerify(static_cast<bool>(statement), #statement, "3rd try", __FILE__, __LINE__))\
                    return;\
    } while (0)

// values chosen at random
static const quint32 RandomValue32 = 0x4d1169f1U;
static const quint64 RandomValue64 = Q_UINT64_C(0x3ce63161b998aa91);
static const double RandomValueFP = double(0.3010463714599609f);

static void setRNGControl(uint v)
{
#ifdef QT_BUILD_INTERNAL
    qt_randomdevice_control.store(v);
#else
    Q_UNUSED(v);
#endif
}

class tst_QRandomGenerator : public QObject
{
    Q_OBJECT

public slots:
    void cleanup() { setRNGControl(0); }

private slots:
    void generate32_data();
    void generate32();
    void generate64_data() { generate32_data(); }
    void generate64();
    void quality_data() { generate32_data(); }
    void quality();
    void fillRangeUInt_data() { generate32_data(); }
    void fillRangeUInt();
    void fillRangeULong_data() { generate32_data(); }
    void fillRangeULong();
    void fillRangeULLong_data() { generate32_data(); }
    void fillRangeULLong();
    void generateUInt_data() { generate32_data(); }
    void generateUInt();
    void generateULLong_data() { generate32_data(); }
    void generateULLong();
    void generateNonContiguous_data() { generate32_data(); }
    void generateNonContiguous();

    void bounded_data();
    void bounded();
    void boundedQuality_data() { generate32_data(); }
    void boundedQuality();

    void generateReal_data() { generate32_data(); }
    void generateReal();
    void qualityReal_data() { generate32_data(); }
    void qualityReal();

    void seedStdRandomEngines();
    void stdUniformIntDistribution_data();
    void stdUniformIntDistribution();
    void stdGenerateCanonical_data() { generateReal_data(); }
    void stdGenerateCanonical();
    void stdUniformRealDistribution_data();
    void stdUniformRealDistribution();
    void stdRandomDistributions();
};

using namespace std;
QT_WARNING_DISABLE_GCC("-Wfloat-equal")
QT_WARNING_DISABLE_CLANG("-Wfloat-equal")

void tst_QRandomGenerator::generate32_data()
{
    QTest::addColumn<uint>("control");
    QTest::newRow("default") << 0U;
#ifdef QT_BUILD_INTERNAL
    QTest::newRow("direct") << uint(SkipMemfill);
    QTest::newRow("system") << uint(SkipHWRNG);
#  ifdef HAVE_FALLBACK_ENGINE
    QTest::newRow("fallback") << uint(SkipHWRNG | SkipSystemRNG);
#  endif
#endif
}

void tst_QRandomGenerator::generate32()
{
    QFETCH(uint, control);
    setRNGControl(control);

    for (int i = 0; i < 4; ++i) {
        QVERIFY_3TIMES([] {
            quint32 value = QRandomGenerator::generate();
            return value != 0 && value != RandomValue32;
        }());
    }

    // and should hopefully be different from repeated calls
    for (int i = 0; i < 4; ++i)
        QVERIFY_3TIMES(QRandomGenerator::generate() != QRandomGenerator::generate());
}

void tst_QRandomGenerator::generate64()
{
    QFETCH(uint, control);
    setRNGControl(control);

    for (int i = 0; i < 4; ++i) {
        QVERIFY_3TIMES([] {
            quint64 value = QRandomGenerator::generate();
            return value != 0 && value != RandomValue32 && value != RandomValue64;
        }());
    }

    // and should hopefully be different from repeated calls
    for (int i = 0; i < 4; ++i)
        QVERIFY_3TIMES(QRandomGenerator::generate64() != QRandomGenerator::generate64());
    for (int i = 0; i < 4; ++i)
        QVERIFY_3TIMES(QRandomGenerator::generate() != quint32(QRandomGenerator::generate64()));
    for (int i = 0; i < 4; ++i)
        QVERIFY_3TIMES(QRandomGenerator::generate() != (QRandomGenerator::generate64() >> 32));
}

void tst_QRandomGenerator::quality()
{
    enum {
        BufferSize = 2048,
        BufferCount = BufferSize / sizeof(quint32),

        // if the distribution were perfect, each byte in the buffer would
        // appear exactly:
        PerfectDistribution = BufferSize / (UCHAR_MAX + 1),

        // The chance of a value appearing N times above its perfect
        // distribution is the same as it appearing N times in a row:
        //   N      Probability
        //   1       100%
        //   2       0.390625%
        //   3       15.25 in a million
        //   4       59.60 in a billion
        //   8       5.421e-20
        //   16      2.938e-39

        AcceptableThreshold = 4 * PerfectDistribution,
        FailureThreshold = 16 * PerfectDistribution
    };
    Q_STATIC_ASSERT(FailureThreshold > AcceptableThreshold);

    QFETCH(uint, control);
    setRNGControl(control);

    int histogram[UCHAR_MAX + 1];
    memset(histogram, 0, sizeof(histogram));

    {
        // test the quality of the generator
        quint32 buffer[BufferCount];
        memset(buffer, 0xcc, sizeof(buffer));
        generate_n(buffer, +BufferCount, [] { return QRandomGenerator::generate(); });

        quint8 *ptr = reinterpret_cast<quint8 *>(buffer);
        quint8 *end = ptr + sizeof(buffer);
        for ( ; ptr != end; ++ptr)
            histogram[*ptr]++;
    }

    for (uint i = 0; i < sizeof(histogram)/sizeof(histogram[0]); ++i) {
        int v = histogram[i];
        if (v > AcceptableThreshold)
            qDebug() << i << "above threshold:" << v;
        QVERIFY2(v < FailureThreshold, QByteArray::number(i));
    }
    qDebug() << "Average:" << (std::accumulate(begin(histogram), end(histogram), 0) / (1. * (UCHAR_MAX + 1)))
             << "(expected" << int(PerfectDistribution) << "ideally)"
             << "Max:" << *std::max_element(begin(histogram), end(histogram))
             << "at" << std::max_element(begin(histogram), end(histogram)) - histogram
             << "Min:" << *std::min_element(begin(histogram), end(histogram))
             << "at" << std::min_element(begin(histogram), end(histogram)) - histogram;
}

template <typename T> void fillRange_template()
{
    QFETCH(uint, control);
    setRNGControl(control);

    for (int i = 0; i < 4; ++i) {
        QVERIFY_3TIMES([] {
            T value[1] = { RandomValue32 };
            QRandomGenerator::fillRange(value);
            return value[0] != 0 && value[0] != RandomValue32;
        }());
    }

    for (int i = 0; i < 4; ++i) {
        QVERIFY_3TIMES([] {
            T array[2] = {};
            QRandomGenerator::fillRange(array);
            return array[0] != array[1];
        }());
    }

    if (sizeof(T) > sizeof(quint32)) {
        // just to shut up a warning about shifting uint more than the width
        enum { Shift = sizeof(T) / 2 * CHAR_BIT };
        QVERIFY_3TIMES([] {
            T value[1] = { };
            QRandomGenerator::fillRange(value);
            return quint32(value[0] >> Shift) != quint32(value[0]);
        }());
    }

    // fill in a longer range
    auto longerArrayCheck = [] {
        T array[32];
        memset(array, 0, sizeof(array));
        QRandomGenerator::fillRange(array);
        if (sizeof(T) == sizeof(RandomValue64)
                && find(begin(array), end(array), RandomValue64) != end(array))
            return false;
        return find(begin(array), end(array), 0) == end(array) &&
                find(begin(array), end(array), RandomValue32) == end(array);
    };
    QVERIFY_3TIMES(longerArrayCheck());
}

void tst_QRandomGenerator::fillRangeUInt() { fillRange_template<uint>(); }
void tst_QRandomGenerator::fillRangeULong() { fillRange_template<ulong>(); }
void tst_QRandomGenerator::fillRangeULLong() { fillRange_template<qulonglong>(); }

template <typename T> void generate_template()
{
    QFETCH(uint, control);
    setRNGControl(control);

    // almost the same as fillRange, but limited to 32 bits
    for (int i = 0; i < 4; ++i) {
        QVERIFY_3TIMES([] {
            T value[1] = { RandomValue32 };
            QRandomGenerator().generate(begin(value), end(value));
            return value[0] != 0 && value[0] != RandomValue32
                    && value[0] <= numeric_limits<quint32>::max();
        }());
    }

    // fill in a longer range
    auto longerArrayCheck = [] {
        T array[72] = {};   // at least 256 bytes
        QRandomGenerator().generate(begin(array), end(array));
        return find_if(begin(array), end(array), [](T cur) {
                return cur == 0 || cur == RandomValue32 ||
                        cur == RandomValue64 || cur > numeric_limits<quint32>::max();
            }) == end(array);
    };
    QVERIFY_3TIMES(longerArrayCheck());
}

void tst_QRandomGenerator::generateUInt() { generate_template<uint>(); }
void tst_QRandomGenerator::generateULLong() { generate_template<qulonglong>(); }

void tst_QRandomGenerator::generateNonContiguous()
{
    QFETCH(uint, control);
    setRNGControl(control);

    QLinkedList<quint64> list = { 0, 0, 0, 0,  0, 0, 0, 0 };
    auto longerArrayCheck = [&] {
        QRandomGenerator().generate(list.begin(), list.end());
        return find_if(list.begin(), list.end(), [](quint64 cur) {
                return cur == 0 || cur == RandomValue32 ||
                        cur == RandomValue64 || cur > numeric_limits<quint32>::max();
            }) == list.end();
    };
    QVERIFY_3TIMES(longerArrayCheck());
}

void tst_QRandomGenerator::bounded_data()
{
#ifndef QT_BUILD_INTERNAL
    QSKIP("Test only possible in developer builds");
#endif

    QTest::addColumn<uint>("control");
    QTest::addColumn<quint32>("sup");
    QTest::addColumn<quint32>("expected");

    auto newRow = [](quint32 val, quint32 sup) {
        // calculate the scaled value
        quint64 scaled = val;
        scaled <<= 32;
        scaled /= sup;
        unsigned shifted = unsigned(scaled);
        Q_ASSERT(val < sup);
        Q_ASSERT((shifted & RandomDataMask) == shifted);

        unsigned control = SetRandomData | shifted;
        QTest::addRow("%u,%u", val, sup) << control << sup << val;
    };

    // useless: we can only generate zeroes:
    newRow(0, 1);

    newRow(25, 200);
    newRow(50, 200);
    newRow(75, 200);
}

void tst_QRandomGenerator::bounded()
{
    QFETCH(uint, control);
    QFETCH(quint32, sup);
    QFETCH(quint32, expected);
    setRNGControl(control);

    quint32 value = QRandomGenerator::bounded(sup);
    QVERIFY(value < sup);
    QCOMPARE(value, expected);

    int ivalue = QRandomGenerator::bounded(sup);
    QVERIFY(ivalue < int(sup));
    QCOMPARE(ivalue, int(expected));

    // confirm only the bound now
    setRNGControl(control & (SkipHWRNG|SkipSystemRNG|SkipMemfill));
    value = QRandomGenerator::bounded(sup);
    QVERIFY(value < sup);

    value = QRandomGenerator::bounded(sup / 2, 3 * sup / 2);
    QVERIFY(value >= sup / 2);
    QVERIFY(value < 3 * sup / 2);

    ivalue = QRandomGenerator::bounded(-int(sup), int(sup));
    QVERIFY(ivalue >= -int(sup));
    QVERIFY(ivalue < int(sup));

    // wholly negative range
    ivalue = QRandomGenerator::bounded(-int(sup), 0);
    QVERIFY(ivalue >= -int(sup));
    QVERIFY(ivalue < 0);
}

void tst_QRandomGenerator::boundedQuality()
{
    enum { Bound = 283 };       // a prime number
    enum {
        BufferCount = Bound * 32,

        // if the distribution were perfect, each byte in the buffer would
        // appear exactly:
        PerfectDistribution = BufferCount / Bound,

        // The chance of a value appearing N times above its perfect
        // distribution is the same as it appearing N times in a row:
        //   N      Probability
        //   1       100%
        //   2       0.390625%
        //   3       15.25 in a million
        //   4       59.60 in a billion
        //   8       5.421e-20
        //   16      2.938e-39

        AcceptableThreshold = 4 * PerfectDistribution,
        FailureThreshold = 16 * PerfectDistribution
    };
    Q_STATIC_ASSERT(FailureThreshold > AcceptableThreshold);

    QFETCH(uint, control);
    setRNGControl(control);

    int histogram[Bound];
    memset(histogram, 0, sizeof(histogram));

    {
        // test the quality of the generator
        QVector<quint32> buffer(BufferCount, 0xcdcdcdcd);
        generate(buffer.begin(), buffer.end(), [] { return QRandomGenerator::bounded(Bound); });

        for (quint32 value : qAsConst(buffer)) {
            QVERIFY(value < Bound);
            histogram[value]++;
        }
    }

    for (unsigned i = 0; i < sizeof(histogram)/sizeof(histogram[0]); ++i) {
        int v = histogram[i];
        if (v > AcceptableThreshold)
            qDebug() << i << "above threshold:" << v;
        QVERIFY2(v < FailureThreshold, QByteArray::number(i));
    }

    qDebug() << "Average:" << (std::accumulate(begin(histogram), end(histogram), 0) / qreal(Bound))
             << "(expected" << int(PerfectDistribution) << "ideally)"
             << "Max:" << *std::max_element(begin(histogram), end(histogram))
             << "at" << std::max_element(begin(histogram), end(histogram)) - histogram
             << "Min:" << *std::min_element(begin(histogram), end(histogram))
             << "at" << std::min_element(begin(histogram), end(histogram)) - histogram;
}

void tst_QRandomGenerator::generateReal()
{
    QFETCH(uint, control);
    setRNGControl(control);

    for (int i = 0; i < 4; ++i) {
        QVERIFY_3TIMES([] {
            qreal value = QRandomGenerator::generateDouble();
            return value >= 0 && value < 1 && value != RandomValueFP;
        }());
    }

    // and should hopefully be different from repeated calls
    for (int i = 0; i < 4; ++i)
        QVERIFY_3TIMES(QRandomGenerator::generateDouble() != QRandomGenerator::generateDouble());
}

void tst_QRandomGenerator::qualityReal()
{
    QFETCH(uint, control);
    setRNGControl(control);

    enum {
        SampleSize = 160,

        // Expected value: sample size times proportion of the range:
        PerfectOctile = SampleSize / 8,
        PerfectHalf = SampleSize / 2,

        // Variance is (1 - proportion of range) * expected; sqrt() for standard deviations.
        // Should usually be within twice that and almost never outside four times:
        RangeHalf = 25,         // floor(4 * sqrt((1 - 0.5) * PerfectHalf))
        RangeOctile = 16        // floor(4 * sqrt((1 - 0.125) * PerfectOctile))
    };

    double data[SampleSize];
    std::generate(std::begin(data), std::end(data), &QRandomGenerator::generateDouble);

    int aboveHalf = 0;
    int belowOneEighth = 0;
    int aboveSevenEighths = 0;
    for (double x : data) {
        aboveHalf += x >= 0.5;
        belowOneEighth += x < 0.125;
        aboveSevenEighths += x >= 0.875;

        // these are strict requirements
        QVERIFY(x >= 0);
        QVERIFY(x < 1);
    }

    qInfo("Halfway distribution: %.1f - %.1f", 100. * aboveHalf / SampleSize, 100 - 100. * aboveHalf / SampleSize);
    qInfo("%.1f below 1/8 (expected 12.5%% ideally)", 100. * belowOneEighth / SampleSize);
    qInfo("%.1f above 7/8 (expected 12.5%% ideally)", 100. * aboveSevenEighths / SampleSize);

    QVERIFY(aboveHalf < PerfectHalf + RangeHalf);
    QVERIFY(aboveHalf > PerfectHalf - RangeHalf);
    QVERIFY(aboveSevenEighths < PerfectOctile + RangeOctile);
    QVERIFY(aboveSevenEighths > PerfectOctile - RangeOctile);
    QVERIFY(belowOneEighth < PerfectOctile + RangeOctile);
    QVERIFY(belowOneEighth > PerfectOctile - RangeOctile);
}

template <typename Engine> void seedStdRandomEngine()
{
    QRandomGenerator rd;
    Engine e(rd);
    QVERIFY_3TIMES(e() != 0);

    e.seed(rd);
    QVERIFY_3TIMES(e() != 0);
}

void tst_QRandomGenerator::seedStdRandomEngines()
{
    seedStdRandomEngine<std::default_random_engine>();
    seedStdRandomEngine<std::minstd_rand0>();
    seedStdRandomEngine<std::minstd_rand>();
    seedStdRandomEngine<std::mt19937>();
    seedStdRandomEngine<std::mt19937_64>();
    seedStdRandomEngine<std::ranlux24_base>();
    seedStdRandomEngine<std::ranlux48_base>();
    seedStdRandomEngine<std::ranlux24>();
    seedStdRandomEngine<std::ranlux48>();
}

void tst_QRandomGenerator::stdUniformIntDistribution_data()
{
#ifndef QT_BUILD_INTERNAL
    QSKIP("Test only possible in developer builds");
#endif

    QTest::addColumn<uint>("control");
    QTest::addColumn<quint32>("max");

    auto newRow = [](quint32 max) {
        QTest::addRow("default:%u", max) << 0U << max;
        QTest::addRow("direct:%u", max) << uint(SkipMemfill) << max;
        QTest::addRow("system:%u", max) << uint(SkipHWRNG) << max;
    #ifdef HAVE_FALLBACK_ENGINE
        QTest::addRow("fallback:%u", max) << uint(SkipHWRNG | SkipSystemRNG) << max;
    #endif
    };

    // useless: we can only generate zeroes:
    newRow(0);

    newRow(1);
    newRow(199);
    newRow(numeric_limits<quint32>::max());
}

void tst_QRandomGenerator::stdUniformIntDistribution()
{
    QFETCH(uint, control);
    QFETCH(quint32, max);
    setRNGControl(control & (SkipHWRNG|SkipSystemRNG|SkipMemfill));

    {
        QRandomGenerator rd;
        {
            std::uniform_int_distribution<quint32> dist(0, max);
            quint32 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }
        if ((3 * max / 2) > max) {
            std::uniform_int_distribution<quint32> dist(max / 2, 3 * max / 2);
            quint32 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }

        {
            std::uniform_int_distribution<quint64> dist(0, quint64(max) << 32);
            quint64 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }
        {
            std::uniform_int_distribution<quint64> dist(max / 2, 3 * quint64(max) / 2);
            quint64 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }
    }

    {
        QRandomGenerator64 rd;
        {
            std::uniform_int_distribution<quint32> dist(0, max);
            quint32 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }
        if ((3 * max / 2) > max) {
            std::uniform_int_distribution<quint32> dist(max / 2, 3 * max / 2);
            quint32 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }

        {
            std::uniform_int_distribution<quint64> dist(0, quint64(max) << 32);
            quint64 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }
        {
            std::uniform_int_distribution<quint64> dist(max / 2, 3 * quint64(max) / 2);
            quint64 value = dist(rd);
            QVERIFY(value >= dist.min());
            QVERIFY(value <= dist.max());
        }
    }
}

void tst_QRandomGenerator::stdGenerateCanonical()
{
#if defined(Q_CC_MSVC) && Q_CC_MSVC < 1900
    // see https://connect.microsoft.com/VisualStudio/feedback/details/811611
    QSKIP("MSVC 2013's std::generate_canonical is broken");
#else
    QFETCH(uint, control);
    setRNGControl(control);

    for (int i = 0; i < 4; ++i) {
        QVERIFY_3TIMES([] {
            QRandomGenerator rd;
            qreal value = std::generate_canonical<qreal COMMA 32>(rd);
            return value > 0 && value < 1 && value != RandomValueFP;
        }());
    }

    // and should hopefully be different from repeated calls
    QRandomGenerator rd;
    for (int i = 0; i < 4; ++i)
        QVERIFY_3TIMES(std::generate_canonical<qreal COMMA 32>(rd) !=
                std::generate_canonical<qreal COMMA 32>(rd));
#endif
}

void tst_QRandomGenerator::stdUniformRealDistribution_data()
{
#ifndef QT_BUILD_INTERNAL
    QSKIP("Test only possible in developer builds");
#endif

    QTest::addColumn<uint>("control");
    QTest::addColumn<double>("min");
    QTest::addColumn<double>("sup");

    auto newRow = [](double min, double sup) {
        QTest::addRow("default:%g-%g", min, sup) << 0U << min << sup;
        QTest::addRow("direct:%g-%g", min, sup) << uint(SkipMemfill) << min << sup;
        QTest::addRow("system:%g-%g", min, sup) << uint(SkipHWRNG) << min << sup;
    #ifdef HAVE_FALLBACK_ENGINE
        QTest::addRow("fallback:%g-%g", min, sup) << uint(SkipHWRNG | SkipSystemRNG) << min << sup;
    #endif
    };

    newRow(0, 0);   // useless: we can only generate zeroes
    newRow(0, 1);   // canonical
    newRow(0, 200);
    newRow(0, numeric_limits<quint32>::max() + 1.);
    newRow(0, numeric_limits<quint64>::max() + 1.);
    newRow(-1, 1.6);
}

void tst_QRandomGenerator::stdUniformRealDistribution()
{
    QFETCH(uint, control);
    QFETCH(double, min);
    QFETCH(double, sup);
    setRNGControl(control & (SkipHWRNG|SkipSystemRNG|SkipMemfill));

    {
        QRandomGenerator rd;
        {
            std::uniform_real_distribution<double> dist(min, sup);
            double value = dist(rd);
            QVERIFY(value >= dist.min());
            if (min != sup)
                QVERIFY(value < dist.max());
        }
    }

    {
        QRandomGenerator64 rd;
        {
            std::uniform_real_distribution<double> dist(min, sup);
            double value = dist(rd);
            QVERIFY(value >= dist.min());
            if (min != sup)
                QVERIFY(value < dist.max());
        }
    }
}

void tst_QRandomGenerator::stdRandomDistributions()
{
    // just a compile check for some of the distributions, besides
    // std::uniform_int_distribution and std::uniform_real_distribution (tested
    // above)

    QRandomGenerator rd;

    std::bernoulli_distribution()(rd);

    std::binomial_distribution<quint32>()(rd);
    std::binomial_distribution<quint64>()(rd);

    std::negative_binomial_distribution<quint32>()(rd);
    std::negative_binomial_distribution<quint64>()(rd);

    std::poisson_distribution<int>()(rd);
    std::poisson_distribution<qint64>()(rd);

    std::normal_distribution<qreal>()(rd);

    {
        std::discrete_distribution<int> discrete{0, 1, 1, 10000, 2};
        QVERIFY(discrete(rd) != 0);
        QVERIFY_3TIMES(discrete(rd) == 3);
    }
}

QTEST_APPLESS_MAIN(tst_QRandomGenerator)

#include "tst_qrandomgenerator.moc"