-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
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
Disallow reader.readStruct
for packed structs
#12960
Comments
Just ran into this - seems like a significant footgun. I'm not sure why a packed struct would need padding at the end if that struct has a bit length divisible by 8. For now, I'm using the following function to get the desired behavior: fn readPackedStruct(reader: anytype, comptime T: type) !T {
comptime {
if (@typeInfo(T).Struct.layout != .Packed) @compileError("readPackedStruct: " ++ @typeName(T) ++ " is not a packed struct!");
if (@bitSizeOf(T) % 8 != 0) @compileError("readPackedStruct: " ++ @typeName(T) ++ " has a non-byte-aligned length!");
}
var buffer: [@bitSizeOf(T) / 8]u8 = undefined;
try reader.readNoEof(&buffer);
return @ptrCast(*align(1) T, &buffer).*;
} |
I'm using this as a workaround: const bytes = try reader.readBytesNoEof(@divExact(@bitSizeOf(T), 8));
var result: T= undefined;
@memcpy(std.mem.asBytes(&result), bytes[0..], @divExact(@bitSizeOf(T), 8)); |
imo |
I have the same issue
Documentation says on packed structs "There is no padding between fields." |
|
reader.readStruct
for packed structs
i recently hit this footgun pretty hard (ethernet headers), are we still interested in making this change? I am happy to submit a PR. I assume this change would be considered "breaking"? |
Zig Version
0.9.1 (windows, chocolatey),0.10.0-dev.4166+cae76d829
Steps to Reproduce
zig test repro.zig
Expected Behavior
Test passes.
Log output should be
14. 14
Actual Behavior
Test fails. Log output is
16, 14
.This is because
@sizeOf(PackedStruct)
is 16.However, using sizeOf in readStruct is undesirable for reading consecutive packed structs, because now the seeker position is wrong, affecting future reads downstream. To correct this manually, the developer has to check if packed struct requires padding, and manually wind the seeker back using
seekBy
.The text was updated successfully, but these errors were encountered: