Comment by tremon
1 day ago
But doesn't that show why this is a bad idea? If I understand correctly, this code:
const MyUnion = packed union {
full: u16,
bytes: [2]u8,
};
const value: u16 = 0x55aa;
const in_union: MyUnion = @bitCast(value);
const without_union: [2]u8 = @bitCast(value);
std.debug.assert(without_union[0] == in_union.bytes[0]);
std.debug.assert(without_union[1] == in_union.bytes[1]);
...will now succeed or fail depending on the endianness of the target. That looks like the type of footgun that will bring decades of joy.
zig does not allow arrays in packed structs/unions specifically for endianness reasons (there may be other reasons as well but endianness is what i know of)
Ah, that is useful to know. Is that documented somewhere? From what I can quickly find in the obvious place [0], the only requirement is that "all fields in a packed union must have the same @bitSizeOf" and [2]u8 does satisfy that requirement.
[0] https://ziglang.org/documentation/0.16.0/#packed-union
no, but the documentation for packed structs gives the list of allowed field types. it's also not documented that packed union fields must be valid packed struct fields but people may be able to assume that
edit: also, this is a relevant issue: https://github.com/ziglang/zig/issues/12547
I wonder if packed union also got/will get the same "logical bits" treatment?
My understanding is that the "logical bits" view breaks down for unions, because the nth logical bit could be at different offsets depending on the union variant that's considered active.