authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2024-10-31 02:32:34+00:00
committergravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2024-10-31 20:42:53+00:00
log24babde746621492c5111ffcd8edf575cb176d65
treec5f7affd52d47632874da1f533c888ef648e8304
parentd11bbde5f9c64ef58405604601d55f88bb5d5f3a
signaturelock-open Commit is signed but in an unrecognized format.

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 files changed, 3 insertions(+), 1 deletions(-)

lib/std/mem.zig+3-1
...@@ -3965,7 +3965,9 @@ fn CopyPtrAttrs(...@@ -3965,7 +3965,9 @@ fn CopyPtrAttrs(
3965}3965}
39663966
3967fn AsBytesReturnType(comptime P: type) type {3967fn AsBytesReturnType(comptime P: type) type {
3968 const size = @sizeOf(std.meta.Child(P));3968 const pointer = @typeInfo(P).pointer;
3969 assert(pointer.size == .One);
3970 const size = @sizeOf(pointer.child);
3969 return CopyPtrAttrs(P, .One, [size]u8);3971 return CopyPtrAttrs(P, .One, [size]u8);
3970}3972}
39713973