QRandomGenerator: assert that bounded() calls have correct arguments

Otherwise, the math will fail badly. Documentation improved to reflect
reality.

Change-Id: I9e3d261ad9bf41cfb2b6fffd159085cd38e3c388
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Thiago Macieira 2019-03-29 12:49:47 -07:00
parent 57eed823e4
commit 5d7e221bbf
2 changed files with 19 additions and 9 deletions

View File

@ -903,6 +903,10 @@ inline QRandomGenerator::SystemGenerator &QRandomGenerator::SystemGenerator::sel
\snippet code/src_corelib_global_qrandom.cpp 12
If the \a highest parameter is negative, the result will be negative too;
if it is infinite or NaN, the result will be infinite or NaN too (that is,
not random).
\sa generateDouble(), bounded()
*/
@ -934,7 +938,7 @@ inline QRandomGenerator::SystemGenerator &QRandomGenerator::SystemGenerator::sel
\overload
Generates one random 32-bit quantity in the range between 0 (inclusive) and
\a highest (exclusive). \a highest must not be negative.
\a highest (exclusive). \a highest must be positive.
Note that this function cannot be used to obtain values in the full 32-bit
range of int. Instead, use generate() and cast to int.
@ -946,8 +950,11 @@ inline QRandomGenerator::SystemGenerator &QRandomGenerator::SystemGenerator::sel
\fn quint32 QRandomGenerator::bounded(quint32 lowest, quint32 highest)
\overload
Generates one random 32-bit quantity in the range between \a lowest (inclusive)
and \a highest (exclusive). The same result may also be obtained by using
Generates one random 32-bit quantity in the range between \a lowest
(inclusive) and \a highest (exclusive). The \a highest parameter must be
greater than \a lowest.
The same result may also be obtained by using
\l{http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution}{\c std::uniform_int_distribution}
with parameters \a lowest and \c{\a highest - 1}. That class can also be used to
obtain quantities larger than 32 bits.
@ -968,7 +975,8 @@ inline QRandomGenerator::SystemGenerator &QRandomGenerator::SystemGenerator::sel
\overload
Generates one random 32-bit quantity in the range between \a lowest
(inclusive) and \a highest (exclusive), both of which may be negative.
(inclusive) and \a highest (exclusive), both of which may be negative, but
\a highest must be greater than \a lowest.
Note that this function cannot be used to obtain values in the full 32-bit
range of int. Instead, use generate() and cast to int.

View File

@ -122,16 +122,18 @@ public:
return quint32(value);
}
int bounded(int highest)
{
return int(bounded(quint32(highest)));
}
quint32 bounded(quint32 lowest, quint32 highest)
{
Q_ASSERT(highest > lowest);
return bounded(highest - lowest) + lowest;
}
int bounded(int highest)
{
Q_ASSERT(highest > 0);
return int(bounded(0U, quint32(highest)));
}
int bounded(int lowest, int highest)
{
return bounded(highest - lowest) + lowest;