Skip to content

Commit e0ba8b8

Browse files
authored
std: fix bug in Pcg32 fill function (#13894)
The PCG32 fill function seems to have been copy-pasted from code using u64, so requesting `n` bytes where `(n & 7) > 4` bytes would cause the last few bytes to be all 0.
1 parent 4832677 commit e0ba8b8

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

lib/std/rand/Pcg.zig

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ fn seedTwo(self: *Pcg, init_s: u64, init_i: u64) void {
5151

5252
pub fn fill(self: *Pcg, buf: []u8) void {
5353
var i: usize = 0;
54-
const aligned_len = buf.len - (buf.len & 7);
54+
const aligned_len = buf.len - (buf.len & 3);
5555

5656
// Complete 4 byte segments.
5757
while (i < aligned_len) : (i += 4) {
@@ -108,11 +108,15 @@ test "pcg fill" {
108108
3247963454,
109109
};
110110

111-
for (seq) |s| {
112-
var buf0: [4]u8 = undefined;
113-
var buf1: [3]u8 = undefined;
114-
std.mem.writeIntLittle(u32, &buf0, s);
111+
var i: u32 = 0;
112+
while (i < seq.len) : (i += 2) {
113+
var buf0: [8]u8 = undefined;
114+
std.mem.writeIntLittle(u32, buf0[0..4], seq[i]);
115+
std.mem.writeIntLittle(u32, buf0[4..8], seq[i + 1]);
116+
117+
var buf1: [7]u8 = undefined;
115118
r.fill(&buf1);
116-
try std.testing.expect(std.mem.eql(u8, buf0[0..3], buf1[0..]));
119+
120+
try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..]));
117121
}
118122
}

0 commit comments

Comments
 (0)