authorgravatar for erik.arvstedt@gmail.comErik Arvstedt <erik.arvstedt@gmail.com> 2022-05-12 16:00:35+02:00
committergravatar for erik.arvstedt@gmail.comErik Arvstedt <erik.arvstedt@gmail.com> 2022-05-12 16:23:39+02:00
log23ef7a80601d553bc9cce24500c9d079883867a4
tree413e4a65ba2bdfaec792212f5c39f1346fe03809
parent1d5ea10bee39c6378c5d41597ed477075c3c667f

std.rand.float: simplify leading zero calculations

This saves a `bitwise or` operation in the common case and removes the (slightly magic) mask constants.

1 files changed, 6 insertions(+), 5 deletions(-)

lib/std/rand.zig+6-5
...@@ -256,12 +256,12 @@ pub const Random = struct {...@@ -256,12 +256,12 @@ pub const Random = struct {
256 // If all 41 bits are zero, generate additional random bits, until a256 // If all 41 bits are zero, generate additional random bits, until a
257 // set bit is found, or 126 bits have been generated.257 // set bit is found, or 126 bits have been generated.
258 const rand = r.int(u64);258 const rand = r.int(u64);
259 var rand_lz = @clz(u64, rand | 0x7FFFFF);259 var rand_lz = @clz(u64, rand);
260 if (rand_lz == 41) {260 if (rand_lz >= 41) {
261 // TODO: when #5177 or #489 is implemented,261 // TODO: when #5177 or #489 is implemented,
262 // tell the compiler it is unlikely (1/2^41) to reach this point.262 // tell the compiler it is unlikely (1/2^41) to reach this point.
263 // (Same for the if branch and the f64 calculations below.)263 // (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));
265 if (rand_lz == 41 + 64) {265 if (rand_lz == 41 + 64) {
266 // It is astronomically unlikely to reach this point.266 // It is astronomically unlikely to reach this point.
267 rand_lz += @clz(u32, r.int(u32) | 0x7FF);267 rand_lz += @clz(u32, r.int(u32) | 0x7FF);
...@@ -276,8 +276,9 @@ pub const Random = struct {...@@ -276,8 +276,9 @@ pub const Random = struct {
276 // If all 12 bits are zero, generate additional random bits, until a276 // If all 12 bits are zero, generate additional random bits, until a
277 // set bit is found, or 1022 bits have been generated.277 // set bit is found, or 1022 bits have been generated.
278 const rand = r.int(u64);278 const rand = r.int(u64);
279 var rand_lz: u64 = @clz(u64, rand | 0xFFFFFFFFFFFFF);279 var rand_lz: u64 = @clz(u64, rand);
280 if (rand_lz == 12) {280 if (rand_lz >= 12) {
281 rand_lz = 12;
281 while (true) {282 while (true) {
282 // It is astronomically unlikely for this loop to execute more than once.283 // It is astronomically unlikely for this loop to execute more than once.
283 const addl_rand_lz = @clz(u64, r.int(u64));284 const addl_rand_lz = @clz(u64, r.int(u64));