diff options
| author | Mahdi Rakhshandehroo <24380301+mrakh@users.noreply.github.com> | 2021-12-27 19:13:15 -0500 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2022-05-10 18:50:12 -0700 |
| commit | 550888e2ac0dca25b5d736676bfe3ee9d4c8a8ec (patch) | |
| tree | c6d0620f70f048cfcb14c2a33c835051a9fd33ba /lib/std/rand/Dilbert.zig | |
| parent | e0a514df41cdf40b0e99ba48b86143bfc03dd3aa (diff) | |
| download | zig-550888e2ac0dca25b5d736676bfe3ee9d4c8a8ec.tar.gz zig-550888e2ac0dca25b5d736676bfe3ee9d4c8a8ec.zip | |
std: improve random float generation
Diffstat (limited to 'lib/std/rand/Dilbert.zig')
| -rw-r--r-- | lib/std/rand/Dilbert.zig | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/lib/std/rand/Dilbert.zig b/lib/std/rand/Dilbert.zig new file mode 100644 index 0000000000..dd07a4ceb3 --- /dev/null +++ b/lib/std/rand/Dilbert.zig @@ -0,0 +1,52 @@ +//! Dilbert PRNG +//! Do not use this PRNG! It is meant to be predictable, for the purposes of test reproducibility and coverage. +//! Its output is just a repeat of a user-specified byte pattern. +//! Name is a reference to this comic: https://dilbert.com/strip/2001-10-25 + +const std = @import("std"); +const Random = std.rand.Random; +const math = std.math; +const Dilbert = @This(); + +pattern: []const u8 = undefined, +curr_idx: usize = 0, + +pub fn init(pattern: []const u8) !Dilbert { + if (pattern.len == 0) + return error.EmptyPattern; + var self = Dilbert{}; + self.pattern = pattern; + self.curr_idx = 0; + return self; +} + +pub fn random(self: *Dilbert) Random { + return Random.init(self, fill); +} + +pub fn fill(self: *Dilbert, buf: []u8) void { + for (buf) |*byte| { + byte.* = self.pattern[self.curr_idx]; + self.curr_idx = (self.curr_idx + 1) % self.pattern.len; + } +} + +test "Dilbert fill" { + var r = try Dilbert.init("9nine"); + + const seq = [_]u64{ + 0x396E696E65396E69, + 0x6E65396E696E6539, + 0x6E696E65396E696E, + 0x65396E696E65396E, + 0x696E65396E696E65, + }; + + for (seq) |s| { + var buf0: [8]u8 = undefined; + var buf1: [8]u8 = undefined; + std.mem.writeIntBig(u64, &buf0, s); + r.fill(&buf1); + try std.testing.expect(std.mem.eql(u8, buf0[0..], buf1[0..])); + } +} |
