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.

enumValueWithIndex

Returns a random value from an enum, evenly distributed.

An index into an array of all named values is generated using the specified Index type to determine the return value. This allows for results to be independent of usize representation.

Prefer enumValue if this isn't important.

See uintLessThan, which this function uses in most cases, for commentary on the runtime of this function.

Random.enumValueWithIndex
pub fn enumValueWithIndex(r: Random, comptime EnumType: type, comptime Index: type) EnumType

File

lib/std/Random.zig:105

Code

pub fn enumValueWithIndex(r: Random, comptime EnumType: type, comptime Index: type) EnumType {
    comptime assert(@typeInfo(EnumType) == .@"enum");

    // We won't use int -> enum casting because enum elements can have
    //  arbitrary values.  Instead we'll randomly pick one of the type's values.
    const values = comptime std.enums.values(EnumType);
    comptime assert(values.len > 0); // can't return anything
    comptime assert(maxInt(Index) >= values.len - 1); // can't access all values
    if (values.len == 1) return values[0];

    const index = if (comptime values.len - 1 == maxInt(Index))
        r.int(Index)
    else
        r.uintLessThan(Index, values.len);

    const MinInt = MinArrayIndex(Index);
    return values[@as(MinInt, @intCast(index))];
}