From 23ef7a80601d553bc9cce24500c9d079883867a4 Mon Sep 17 00:00:00 2001 From: Erik Arvstedt Date: Thu, 12 May 2022 16:00:35 +0200 Subject: [PATCH] std.rand.float: simplify leading zero calculations This saves a `bitwise or` operation in the common case and removes the (slightly magic) mask constants. --- lib/std/rand.zig | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/std/rand.zig b/lib/std/rand.zig index e3c97bf385..980722cdff 100644 --- a/lib/std/rand.zig +++ b/lib/std/rand.zig @@ -256,12 +256,12 @@ pub const Random = struct { // If all 41 bits are zero, generate additional random bits, until a // set bit is found, or 126 bits have been generated. const rand = r.int(u64); - var rand_lz = @clz(u64, rand | 0x7FFFFF); - if (rand_lz == 41) { + var rand_lz = @clz(u64, rand); + if (rand_lz >= 41) { // TODO: when #5177 or #489 is implemented, // tell the compiler it is unlikely (1/2^41) to reach this point. // (Same for the if branch and the f64 calculations below.) - rand_lz += @clz(u64, r.int(u64)); + rand_lz = 41 + @clz(u64, r.int(u64)); if (rand_lz == 41 + 64) { // It is astronomically unlikely to reach this point. rand_lz += @clz(u32, r.int(u32) | 0x7FF); @@ -276,8 +276,9 @@ pub const Random = struct { // If all 12 bits are zero, generate additional random bits, until a // set bit is found, or 1022 bits have been generated. const rand = r.int(u64); - var rand_lz: u64 = @clz(u64, rand | 0xFFFFFFFFFFFFF); - if (rand_lz == 12) { + var rand_lz: u64 = @clz(u64, rand); + if (rand_lz >= 12) { + rand_lz = 12; while (true) { // It is astronomically unlikely for this loop to execute more than once. const addl_rand_lz = @clz(u64, r.int(u64));