Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

uintLessThan

Returns an evenly distributed random unsigned integer 0 <= i < less_than. This function assumes that the underlying fillFn produces evenly distributed values. Within this assumption, the runtime of this function is exponentially distributed. If fillFn were backed by a true random generator, the runtime of this function would technically be unbounded. However, if fillFn is backed by any evenly distributed pseudo random number generator, this function is guaranteed to return. If you need deterministic runtime bounds, use uintLessThanBiased.

Random.uintLessThan
pub fn uintLessThan(r: Random, comptime T: type, less_than: T) T

File

lib/std/Random.zig:159

Code

pub fn uintLessThan(r: Random, comptime T: type, less_than: T) T {
    comptime assert(@typeInfo(T).int.signedness == .unsigned);
    const bits = @typeInfo(T).int.bits;
    assert(0 < less_than);

    // adapted from:
    //   http://www.pcg-random.org/posts/bounded-rands.html
    //   "Lemire's (with an extra tweak from me)"
    var x = r.int(T);
    var m = math.mulWide(T, x, less_than);
    var l: T = @truncate(m);
    if (l < less_than) {
        var t = -%less_than;

        if (t >= less_than) {
            t -= less_than;
            if (t >= less_than) {
                t %= less_than;
            }
        }
        while (l < t) {
            x = r.int(T);
            m = math.mulWide(T, x, less_than);
            l = @truncate(m);
        }
    }
    return @intCast(m >> bits);
}