Commit 24babde746

mlugg <mlugg@mlugg.co.uk>
2024-10-31 03:32:34
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.
1 parent d11bbde
Changed files (1)
lib
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);
 }