authorgravatar for mdsteele@alum.mit.eduMatthew D. Steele <mdsteele@alum.mit.edu> 2018-08-03 11:44:39-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-08-03 11:44:39-04:00
logc2a08d7c516899b4c794bd6c3fc07ddb22d5876a
treed5c286e30ac12b3c4d775c3c4a830b4f2bb1da79
parent298abbcff86629273f24891d243fb6e503392e8f

Fix the start-less-than-end assertion in std.rand.Random.range (#1325)

The function returns a value in [start, end), but was asserting start <= end instead of start < end. With this fix, range(1, 1) will now assertion error instead of dividing by zero.

1 files changed, 5 insertions(+), 4 deletions(-)

std/rand/index.zig+5-4
......@@ -30,7 +30,7 @@ pub const DefaultCsprng = Isaac64;
3030pub const Random = struct {
3131 fillFn: fn (r: *Random, buf: []u8) void,
3232
33 /// Read random bytes into the specified buffer until fill.
33 /// Read random bytes into the specified buffer until full.
3434 pub fn bytes(r: *Random, buf: []u8) void {
3535 r.fillFn(r, buf);
3636 }
......@@ -48,10 +48,10 @@ pub const Random = struct {
4848 }
4949 }
5050
51 /// Get a random unsigned integer with even distribution between `start`
52 /// inclusive and `end` exclusive.
51 /// Return a random integer with even distribution between `start`
52 /// inclusive and `end` exclusive. `start` must be less than `end`.
5353 pub fn range(r: *Random, comptime T: type, start: T, end: T) T {
54 assert(start <= end);
54 assert(start < end);
5555 if (T.is_signed) {
5656 const uint = @IntType(false, T.bit_count);
5757 if (start >= 0 and end >= 0) {
......@@ -664,6 +664,7 @@ test "Random range" {
664664 testRange(&prng.random, -4, 3);
665665 testRange(&prng.random, -4, -1);
666666 testRange(&prng.random, 10, 14);
667 // TODO: test that prng.random.range(1, 1) causes an assertion error
667668}
668669
669670fn testRange(r: *Random, start: i32, end: i32) void {