authorgravatar for git@e4m2.come4m2 <git@e4m2.com> 2023-08-15 11:53:48+02:00
committergravatar for git@e4m2.come4m2 <git@e4m2.com> 2023-08-15 11:53:48+02:00
log6f129c9912369d4d7e22647f98e4d88b11b77bf0
tree5982c9749f126eca258049733d7f162b51ab4370
parent9135115573051eff58ffcf1ba0a3cce51ed0b413

std.rand: Accept ints with >64 bits in `uintLessThanBiased`


1 files changed, 3 insertions(+), 10 deletions(-)

lib/std/rand.zig+3-10
...@@ -121,14 +121,8 @@ pub const Random = struct {...@@ -121,14 +121,8 @@ pub const Random = struct {
121 /// The results of this function may be biased.121 /// The results of this function may be biased.
122 pub fn uintLessThanBiased(r: Random, comptime T: type, less_than: T) T {122 pub fn uintLessThanBiased(r: Random, comptime T: type, less_than: T) T {
123 comptime assert(@typeInfo(T).Int.signedness == .unsigned);123 comptime assert(@typeInfo(T).Int.signedness == .unsigned);
124 const bits = @typeInfo(T).Int.bits;
125 comptime assert(bits <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation!
126 assert(0 < less_than);124 assert(0 < less_than);
127 if (bits <= 32) {125 return limitRangeBiased(T, r.int(T), less_than);
128 return @as(T, @intCast(limitRangeBiased(u32, r.int(u32), less_than)));
129 } else {
130 return @as(T, @intCast(limitRangeBiased(u64, r.int(u64), less_than)));
131 }
132 }126 }
133127
134 /// Returns an evenly distributed random unsigned integer `0 <= i < less_than`.128 /// Returns an evenly distributed random unsigned integer `0 <= i < less_than`.
...@@ -438,13 +432,12 @@ pub const Random = struct {...@@ -438,13 +432,12 @@ pub const Random = struct {
438pub fn limitRangeBiased(comptime T: type, random_int: T, less_than: T) T {432pub fn limitRangeBiased(comptime T: type, random_int: T, less_than: T) T {
439 comptime assert(@typeInfo(T).Int.signedness == .unsigned);433 comptime assert(@typeInfo(T).Int.signedness == .unsigned);
440 const bits = @typeInfo(T).Int.bits;434 const bits = @typeInfo(T).Int.bits;
441 const T2 = std.meta.Int(.unsigned, bits * 2);
442435
443 // adapted from:436 // adapted from:
444 // http://www.pcg-random.org/posts/bounded-rands.html437 // http://www.pcg-random.org/posts/bounded-rands.html
445 // "Integer Multiplication (Biased)"438 // "Integer Multiplication (Biased)"
446 var m: T2 = @as(T2, random_int) * @as(T2, less_than);439 const m = math.mulWide(T, random_int, less_than);
447 return @as(T, @intCast(m >> bits));440 return @intCast(m >> bits);
448}441}
449442
450// Generator to extend 64-bit seed values into longer sequences.443// Generator to extend 64-bit seed values into longer sequences.