std.Random: Make ptr optional to avoid UB when comparing Random instances

The same change as the one made to std.Allocator, and for the same reasons. However, this change is precautionary rather than addressing a known instance of UB.
This commit is contained in:
Ryan Liptak 2024-11-24 18:26:30 -08:00
parent be6b89069b
commit 52a6e355c4
2 changed files with 7 additions and 5 deletions

View File

@ -29,8 +29,10 @@ pub const RomuTrio = @import("Random/RomuTrio.zig");
pub const SplitMix64 = @import("Random/SplitMix64.zig");
pub const ziggurat = @import("Random/ziggurat.zig");
ptr: *anyopaque,
fillFn: *const fn (ptr: *anyopaque, buf: []u8) void,
/// The type erased pointer to the random implementation.
/// If null, the random implementation has no associated state.
ptr: ?*anyopaque,
fillFn: *const fn (ptr: ?*anyopaque, buf: []u8) void,
pub fn init(pointer: anytype, comptime fillFn: fn (ptr: @TypeOf(pointer), buf: []u8) void) Random {
const Ptr = @TypeOf(pointer);
@ -38,8 +40,8 @@ pub fn init(pointer: anytype, comptime fillFn: fn (ptr: @TypeOf(pointer), buf: [
assert(@typeInfo(Ptr).pointer.size == .One); // Must be a single-item pointer
assert(@typeInfo(@typeInfo(Ptr).pointer.child) == .@"struct"); // Must point to a struct
const gen = struct {
fn fill(ptr: *anyopaque, buf: []u8) void {
const self: Ptr = @ptrCast(@alignCast(ptr));
fn fill(ptr: ?*anyopaque, buf: []u8) void {
const self: Ptr = @ptrCast(@alignCast(ptr.?));
fillFn(self, buf);
}
};

View File

@ -12,7 +12,7 @@ const posix = std.posix;
/// We use this as a layer of indirection because global const pointers cannot
/// point to thread-local variables.
pub const interface: std.Random = .{
.ptr = undefined,
.ptr = null,
.fillFn = tlsCsprngFill,
};