authorgravatar for justin.whear+github@gmail.comJustin Whear <justin.whear+github@gmail.com> 2021-08-19 12:18:23-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2021-08-19 22:18:23+03:00
log62fe4a0ba8a08b9477e772841d3ae128937f0752
tree763f892c896ceac7e45e6ba3408ccede4116a0e2
parent7e7d67d8eed45bcf3908edd2f4ca864144fffad5
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

std.rand.Random: add enumValue() (#9583)

* add Random.enumValue() * edits suggested by review * applied zig fmt * Rewrite to use std.enums.values Implemented pfgithub's suggestion to rewrite against this function, greatly simplifying the implementation. Co-authored-by: Justin Whear <justin@economicmodeling.com>

1 files changed, 30 insertions(+), 0 deletions(-)

lib/std/rand.zig+30
......@@ -47,6 +47,19 @@ pub const Random = struct {
4747 return r.int(u1) != 0;
4848 }
4949
50 /// Returns a random value from an enum, evenly distributed.
51 pub fn enumValue(r: *Random, comptime EnumType: type) EnumType {
52 if (comptime !std.meta.trait.is(.Enum)(EnumType)) {
53 @compileError("Random.enumValue requires an enum type, not a " ++ @typeName(EnumType));
54 }
55
56 // We won't use int -> enum casting because enum elements can have
57 // arbitrary values. Instead we'll randomly pick one of the type's values.
58 const values = std.enums.values(EnumType);
59 const index = r.uintLessThan(usize, values.len);
60 return values[index];
61 }
62
5063 /// Returns a random int `i` such that `0 <= i <= maxInt(T)`.
5164 /// `i` is evenly distributed.
5265 pub fn int(r: *Random, comptime T: type) T {
......@@ -377,6 +390,23 @@ fn testRandomBoolean() !void {
377390 try expect(r.random.boolean() == true);
378391}
379392
393test "Random enum" {
394 try testRandomEnumValue();
395 comptime try testRandomEnumValue();
396}
397fn testRandomEnumValue() !void {
398 const TestEnum = enum {
399 First,
400 Second,
401 Third,
402 };
403 var r = SequentialPrng.init();
404 r.next_value = 0;
405 try expect(r.random.enumValue(TestEnum) == TestEnum.First);
406 try expect(r.random.enumValue(TestEnum) == TestEnum.First);
407 try expect(r.random.enumValue(TestEnum) == TestEnum.First);
408}
409
380410test "Random intLessThan" {
381411 @setEvalBranchQuota(10000);
382412 try testRandomIntLessThan();