Skip to content

Commit 402c85a

Browse files
committed
std.rand.float: simplify leading zero calculations
This saves one `bitwise or` operation and removes two (slightly magic) mask constants.
1 parent 1d5ea10 commit 402c85a

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

lib/std/rand.zig

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -256,12 +256,12 @@ pub const Random = struct {
256256
// If all 41 bits are zero, generate additional random bits, until a
257257
// set bit is found, or 126 bits have been generated.
258258
const rand = r.int(u64);
259-
var rand_lz = @clz(u64, rand | 0x7FFFFF);
260-
if (rand_lz == 41) {
259+
var rand_lz = @clz(u64, rand);
260+
if (rand_lz >= 41) {
261261
// TODO: when #5177 or #489 is implemented,
262262
// tell the compiler it is unlikely (1/2^41) to reach this point.
263263
// (Same for the if branch and the f64 calculations below.)
264-
rand_lz += @clz(u64, r.int(u64));
264+
rand_lz = 41 + @clz(u64, r.int(u64));
265265
if (rand_lz == 41 + 64) {
266266
// It is astronomically unlikely to reach this point.
267267
rand_lz += @clz(u32, r.int(u32) | 0x7FF);
@@ -276,8 +276,9 @@ pub const Random = struct {
276276
// If all 12 bits are zero, generate additional random bits, until a
277277
// set bit is found, or 1022 bits have been generated.
278278
const rand = r.int(u64);
279-
var rand_lz: u64 = @clz(u64, rand | 0xFFFFFFFFFFFFF);
280-
if (rand_lz == 12) {
279+
var rand_lz: u64 = @clz(u64, rand);
280+
if (rand_lz >= 12) {
281+
rand_lz = 12;
281282
while (true) {
282283
// It is astronomically unlikely for this loop to execute more than once.
283284
const addl_rand_lz = @clz(u64, r.int(u64));

0 commit comments

Comments
 (0)