pub fn enumValueWithIndex(r: Random, comptime EnumType: type, comptime Index: type) EnumType r: RandomEnumType: typeIndex: type105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122pub 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))];
}
Returns a random value from an enum, evenly distributed.
An index into an array of all named values is generated using the specified
Indextype to determine the return value. This allows for results to be independent ofusizerepresentation.Prefer
enumValueif this isn't important.See
uintLessThan, which this function uses in most cases, for commentary on the runtime of this function.