Function intRangeLessThan [src]
Returns an evenly distributed random integer at_least <= i < less_than.
See uintLessThan, which this function uses in most cases,
for commentary on the runtime of this function.
Prototype
pub fn intRangeLessThan(r: Random, comptime T: type, at_least: T, less_than: T) T
Parameters
r: Random
T: type
at_least: T
less_than: T
Source
pub fn intRangeLessThan(r: Random, comptime T: type, at_least: T, less_than: T) T {
assert(at_least < less_than);
const info = @typeInfo(T).int;
if (info.signedness == .signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(.unsigned, info.bits);
const lo: UnsignedT = @bitCast(at_least);
const hi: UnsignedT = @bitCast(less_than);
const result = lo +% r.uintLessThan(UnsignedT, hi -% lo);
return @bitCast(result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintLessThan(T, less_than - at_least);
}
}