Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
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 standard library. Public Function

enumValueWithIndex

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

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.

Params

  • r: Random
  • EnumType: type
  • Index: type

File

Random.zig:105
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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))];
}