LibTest: Minimize footprint of Gen::unsigned_int, simplify code

unsigned_int(0) doesn't need to draw bits from RandomnessSource.

An expression for getting INT_MAX for u32 didn't need to be
special-cased over the general formula.

This is a follow-up on a few comments
This commit is contained in:
Martin Janiczek 2023-10-27 11:41:38 +02:00 committed by Andrew Kaster
parent 230aa1404c
commit 4c068ba921

View file

@ -45,6 +45,9 @@ namespace Gen {
// Shrinks towards 0. // Shrinks towards 0.
inline u32 unsigned_int(u32 max) inline u32 unsigned_int(u32 max)
{ {
if (max == 0)
return 0;
u32 random = Test::randomness_source().draw_value(max, [&]() { u32 random = Test::randomness_source().draw_value(max, [&]() {
return AK::get_random_uniform(max + 1); return AK::get_random_uniform(max + 1);
}); });
@ -58,19 +61,15 @@ inline u32 unsigned_int(u32 max)
// -> value 10, RandomRun [7] // -> value 10, RandomRun [7]
// etc. // etc.
// //
// In case `min == max`, the RandomRun footprint will be smaller, as we'll // In case `min == max`, the RandomRun footprint will be smaller: no randomness
// switch to a `constant` and won't need any randomness to generate that // is needed.
// value:
// //
// Gen::unsigned_int(3,3) -> value 3, RandomRun [] (always) // Gen::unsigned_int(3,3) -> value 3, RandomRun [] (always)
// //
// Shrinks towards the smaller argument. // Shrinks towards the minimum.
inline u32 unsigned_int(u32 min, u32 max) inline u32 unsigned_int(u32 min, u32 max)
{ {
VERIFY(max >= min); VERIFY(max >= min);
if (min == max) {
return min;
}
return unsigned_int(max - min) + min; return unsigned_int(max - min) + min;
} }
@ -174,9 +173,7 @@ inline u32 unsigned_int()
NumericLimits<u32>::max()); NumericLimits<u32>::max());
} }
u32 max = (bits == 32) u32 max = ((u64)1 << bits) - 1;
? NumericLimits<u32>::max()
: ((u64)1 << bits) - 1;
return unsigned_int(max); return unsigned_int(max);
} }