From 24babde746621492c5111ffcd8edf575cb176d65 Mon Sep 17 00:00:00 2001 From: mlugg Date: Thu, 31 Oct 2024 02:32:34 +0000 Subject: [PATCH] std.mem.asBytes: fix footgun when passing non-single pointer I was just bitten by this footgun, where I actually wanted `sliceAsBytes` but unintentionally used `asBytes`, which in practice ignored all but the first element. Just add a comptime assertion to trigger a compile error in this case. --- lib/std/mem.zig | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 65d801a0aa..039b9d4324 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -3965,7 +3965,9 @@ fn CopyPtrAttrs( } fn AsBytesReturnType(comptime P: type) type { - const size = @sizeOf(std.meta.Child(P)); + const pointer = @typeInfo(P).pointer; + assert(pointer.size == .One); + const size = @sizeOf(pointer.child); return CopyPtrAttrs(P, .One, [size]u8); }