Add argument for fillFn to Random.init

As suggested by @leecannon, this provides more flexibility to the
`Random` interface. For exmaple, this allows for an implementation to
provide multiple different fill functions.
This commit is contained in:
ominitay
2021-10-29 00:34:17 +01:00
committed by Andrew Kelley
parent 66b4bd19c0
commit 544d7d9982
7 changed files with 9 additions and 10 deletions

View File

@@ -32,17 +32,16 @@ pub const Random = struct {
ptr: *c_void,
fillFn: fn (ptr: *c_void, buf: []u8) void,
pub fn init(pointer: anytype) Random {
pub fn init(pointer: anytype, comptime fillFn: fn (ptr: @TypeOf(pointer), buf: []u8) void) Random {
const Ptr = @TypeOf(pointer);
assert(@typeInfo(Ptr) == .Pointer); // Must be a pointer
assert(@typeInfo(Ptr).Pointer.size == .One); // Must be a single-item pointer
assert(@typeInfo(@typeInfo(Ptr).Pointer.child) == .Struct); // Must point to a struct
assert(std.meta.trait.hasFn("fill")(@typeInfo(Ptr).Pointer.child)); // Struct must provide the `fill` function
const gen = struct {
fn fill(ptr: *c_void, buf: []u8) void {
const alignment = @typeInfo(Ptr).Pointer.alignment;
const self = @ptrCast(Ptr, @alignCast(alignment, ptr));
self.fill(buf);
fillFn(self, buf);
}
};
@@ -333,7 +332,7 @@ const SequentialPrng = struct {
}
pub fn random(self: *Self) Random {
return Random.init(self);
return Random.init(self, fill);
}
pub fn fill(self: *Self, buf: []u8) void {

View File

@@ -21,7 +21,7 @@ pub fn init(secret_seed: [secret_seed_length]u8) Gimli {
}
pub fn random(self: *Gimli) Random {
return Random.init(self);
return Random.init(self, fill);
}
pub fn fill(self: *Gimli, buf: []u8) void {

View File

@@ -31,7 +31,7 @@ pub fn init(init_s: u64) Isaac64 {
}
pub fn random(self: *Isaac64) Random {
return Random.init(self);
return Random.init(self, fill);
}
fn step(self: *Isaac64, mix: u64, base: usize, comptime m1: usize, comptime m2: usize) void {

View File

@@ -22,7 +22,7 @@ pub fn init(init_s: u64) Pcg {
}
pub fn random(self: *Pcg) Random {
return Random.init(self);
return Random.init(self, fill);
}
fn next(self: *Pcg) u32 {

View File

@@ -24,7 +24,7 @@ pub fn init(init_s: u64) Sfc64 {
}
pub fn random(self: *Sfc64) Random {
return Random.init(self);
return Random.init(self, fill);
}
fn next(self: *Sfc64) u64 {

View File

@@ -17,7 +17,7 @@ pub fn init(init_s: u64) Xoroshiro128 {
}
pub fn random(self: *Xoroshiro128) Random {
return Random.init(self);
return Random.init(self, fill);
}
fn next(self: *Xoroshiro128) u64 {

View File

@@ -19,7 +19,7 @@ pub fn init(init_s: u64) Xoshiro256 {
}
pub fn random(self: *Xoshiro256) Random {
return Random.init(self);
return Random.init(self, fill);
}
fn next(self: *Xoshiro256) u64 {