ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
34.31k stars 2.51k forks source link

Make @bitCast use @bitSizeOf instead of @sizeOf #8102

Closed Exonorid closed 2 years ago

Exonorid commented 3 years ago

Currently, the bitCast builtin function works such that it "Asserts that @sizeOf(@TypeOf(value)) == @sizeOf(DestType)." I'm proposing that this is changed to be bitSizeOf to exclude padding bytes.

Why?

The main place I've found this interferes with programming is bit-casting to an integer which is a non-power of two in size. For example,

const Foo = packed struct {a: u8, b: u16}
const m_foo = Foo{.a = 5, .b = 73}
const as_int: u24 = @bitCast(u24, m_foo);

would not work because u24 is 4 bytes wide according to sizeOf, while Foo is 3 bytes wide, as is expected. Using bitSizeOf, this would compile, since both are 24 bits wide.

Exonorid commented 3 years ago

I made a patch to implement this, and from my testing it appears to work correctly bitCast.patch.txt

andrewrk commented 2 years ago

Rejected for the same reason as #10547.