Skip to content

Commit

Permalink
std.mem.asBytes: fix footgun when passing non-single pointer
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mlugg committed Oct 31, 2024
1 parent 57392a5 commit 5da3d6c
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/std/mem.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down

0 comments on commit 5da3d6c

Please sign in to comment.