Skip to content
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 readStruct for packed structs #21562

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/std/io/Reader.zig
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,9 @@ pub fn isBytes(self: Self, slice: []const u8) anyerror!bool {

pub fn readStruct(self: Self, comptime T: type) anyerror!T {
// Only extern and packed structs have defined in-memory layout.
comptime assert(@typeInfo(T).@"struct".layout != .auto);
// Packed structs may have padding due to alignment of the backing integer.
// Therefore, only extern structs are allowed.
comptime assert(@typeInfo(T).@"struct".layout == .@"extern");
Comment on lines +329 to +331
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Packed structs may have padding due to alignment of the backing integer.
// Therefore, only extern structs are allowed.
comptime assert(@typeInfo(T).@"struct".layout == .@"extern");
comptime assert(@typeInfo(T) == .@"struct");
comptime assert(std.meta.hasUniqueRepresentation(T));

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regular structs do not have a defined field order and the order may be changed by the compiler. This is not a sound suggestion as it will break when such happens.

var res: [1]T = undefined;
try self.readNoEof(mem.sliceAsBytes(res[0..]));
return res[0];
Expand Down