random: add RandomMixin::randbits with compile-known bits

In many cases, it is known at compile time how many bits are requested from
randbits. Provide a variant of randbits that accepts this number as a template,
to make sure the compiler can make use of this knowledge. This is used immediately
in rand32() and randbool(), and a few further call sites.
This commit is contained in:
Pieter Wuille
2024-03-10 12:38:14 -04:00
parent 21ce9d8658
commit ddb7d26cfd
6 changed files with 52 additions and 9 deletions

View File

@@ -1195,7 +1195,7 @@ BOOST_AUTO_TEST_CASE(muhash_tests)
uint256 res;
int table[4];
for (int i = 0; i < 4; ++i) {
table[i] = g_insecure_rand_ctx.randbits(3);
table[i] = g_insecure_rand_ctx.randbits<3>();
}
for (int order = 0; order < 4; ++order) {
MuHash3072 acc;
@@ -1215,8 +1215,8 @@ BOOST_AUTO_TEST_CASE(muhash_tests)
}
}
MuHash3072 x = FromInt(g_insecure_rand_ctx.randbits(4)); // x=X
MuHash3072 y = FromInt(g_insecure_rand_ctx.randbits(4)); // x=X, y=Y
MuHash3072 x = FromInt(g_insecure_rand_ctx.randbits<4>()); // x=X
MuHash3072 y = FromInt(g_insecure_rand_ctx.randbits<4>()); // x=X, y=Y
MuHash3072 z; // x=X, y=Y, z=1
z *= x; // x=X, y=Y, z=X
z *= y; // x=X, y=Y, z=X*Y