Skip to content

OffsetOf incorrect for fields in a packed struct that come after custom sized ints #1408

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
raulgrell opened this issue Aug 24, 2018 · 2 comments
Milestone

Comments

@raulgrell
Copy link
Contributor

const std = @import("std");

const P = packed struct {
    a: u8,
    b: u32,
    c: u8,
    d: u3,
    e: u8,
    f: u16,
    g: u16,
};

test "byteOffsetOf" {
    const p: P = undefined;
    std.debug.warn("\n");
    std.debug.warn("a: {}\n", (usize)(@offsetOf(P, "a")));
    std.debug.warn("b: {}\n", (usize)(@offsetOf(P, "b")));
    std.debug.warn("c: {}\n", (usize)(@offsetOf(P, "c")));
    std.debug.warn("d: {}\n", (usize)(@offsetOf(P, "d")));
    std.debug.warn("e: {}\n", (usize)(@offsetOf(P, "e")));
    std.debug.warn("f: {}\n", (usize)(@offsetOf(P, "f")));
    std.debug.warn("g: {}\n", (usize)(@offsetOf(P, "g")));
}

I was looking at #633 and happened across this bug. d, e, f and g all return 6.

@andrewrk andrewrk added this to the 0.4.0 milestone Aug 25, 2018
@andrewrk
Copy link
Member

andrewrk commented Aug 25, 2018

This might be working as designed - let's discuss.

How it works for packed fields is:

  • The first field that is not byte-aligned is an integer that is byte-aligned, and holds all the fields following until the struct becomes byte-aligned again.
  • @offsetOf and pointers must be byte-aligned, so they point to this byte-aligned integer. Pointers have extra metadata to specify the bit offset. @offsetOf does not currently have a way to represent this information. I believe that is why @bitOffsetOf would exist.

@raulgrell
Copy link
Contributor Author

Makes perfect sense. I just changed e to u5, to align everything again and it behaved as expected. Thanks for the feedback

@andrewrk andrewrk modified the milestones: 0.4.0, 0.3.0 Sep 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants