Skip to content

Commit e4abdf5

Browse files
committed
std.Io.Reader: fix takeStruct/peekStruct packed
closes #24516
1 parent f657767 commit e4abdf5

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

lib/std/Io/Reader.zig

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,7 +1148,7 @@ pub inline fn takeStruct(r: *Reader, comptime T: type, endian: std.builtin.Endia
11481148
return res;
11491149
},
11501150
.@"packed" => {
1151-
return takeInt(r, info.backing_integer.?, endian);
1151+
return @bitCast(try takeInt(r, info.backing_integer.?, endian));
11521152
},
11531153
},
11541154
else => @compileError("not a struct"),
@@ -1173,7 +1173,7 @@ pub inline fn peekStruct(r: *Reader, comptime T: type, endian: std.builtin.Endia
11731173
return res;
11741174
},
11751175
.@"packed" => {
1176-
return peekInt(r, info.backing_integer.?, endian);
1176+
return @bitCast(try peekInt(r, info.backing_integer.?, endian));
11771177
},
11781178
},
11791179
else => @compileError("not a struct"),
@@ -1724,6 +1724,27 @@ test "takeDelimiterInclusive when it rebases" {
17241724
}
17251725
}
17261726

1727+
test "takeStruct and peekStruct packed" {
1728+
var r: Reader = .fixed(&.{ 0b11110000, 0b00110011 });
1729+
const S = packed struct(u16) { a: u2, b: u6, c: u7, d: u1 };
1730+
1731+
try testing.expectEqual(@as(S, .{
1732+
.a = 0b11,
1733+
.b = 0b001100,
1734+
.c = 0b1110000,
1735+
.d = 0b1,
1736+
}), try r.peekStruct(S, .big));
1737+
1738+
try testing.expectEqual(@as(S, .{
1739+
.a = 0b11,
1740+
.b = 0b001100,
1741+
.c = 0b1110000,
1742+
.d = 0b1,
1743+
}), try r.takeStruct(S, .big));
1744+
1745+
try testing.expectError(error.EndOfStream, r.takeStruct(S, .little));
1746+
}
1747+
17271748
/// Provides a `Reader` implementation by passing data from an underlying
17281749
/// reader through `Hasher.update`.
17291750
///

0 commit comments

Comments
 (0)