Proposal: @offsetOf instead of @byteOffsetOf #7794
Labels
accepted
This proposal is planned.
breaking
Implementing this issue could cause existing code to no longer compile or have different behavior.
contributor friendly
This issue is limited in scope and/or knowledge of Zig internals.
proposal
This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone
I believe that the builtin used for getting the byte offset of a struct field should be called
@offsetOf
rather than@byteOffsetOf
. Here are a few reasons why:@sizeOf
/@bitSizeOf
.@alignOf
is also not called@byteAlignOf
.offsetOf
is common in other programming languages. The C macro is calledoffsetof
. There are also a few Rust libraries that provide macros namedoffset_of
.I also believe
@offsetOf
should fail when the struct field is not aligned to a byte boundary. The most obvious reason is to prevent bugs where@byteOffsetOf
is used without checking if the offset is actually a whole number of bytes. Having this check as a part of@offsetOf
will make subtly incorrect code invalid and will make correct code cleaner.Using
@byteOffsetOf
on non-byte-aligned bitfields is rarely useful, and I'd imagine that all such uses will be made more clear by doing@bitOffetOf(T, field) / 8
instead. Even if we keep the current@byteOffsetOf
for backwards compatibility, I believe it should be phased out.A quick
grep
through the standard library revealed that the only uses of@byteOffsetOf
are assertions about the layout ofextern struct
s. This can also be done with the proposed@offsetOf
with the added advantage that if we were to make the structspacked
, we'd automatically make sure that the fields are byte-aligned.The text was updated successfully, but these errors were encountered: