Function peekStruct [src]
Asserts the buffer was initialized with a capacity at least @sizeOf(T).
This function is inline to avoid referencing std.mem.byteSwapAllFields
when endian is comptime-known and matches the host endianness.
See also:
takeStruct
peekStructPointer
Prototype
pub inline fn peekStruct(r: *Reader, comptime T: type, endian: std.builtin.Endian) Error!T
Parameters
r: *Reader
T: type
endian: std.builtin.Endian
Possible Errors
See the Reader
implementation for detailed diagnostics.
Example
test peekStruct {
var r: Reader = .fixed(&.{ 0x12, 0x00, 0x34, 0x56 });
const S = extern struct { a: u8, b: u16 };
try testing.expectEqual(@as(S, .{ .a = 0x12, .b = 0x3456 }), try r.peekStruct(S, .big));
try testing.expectEqual(@as(S, .{ .a = 0x12, .b = 0x5634 }), try r.peekStruct(S, .little));
}
Source
pub inline fn peekStruct(r: *Reader, comptime T: type, endian: std.builtin.Endian) Error!T {
switch (@typeInfo(T)) {
.@"struct" => |info| switch (info.layout) {
.auto => @compileError("ill-defined memory layout"),
.@"extern" => {
var res = (try r.peekStructPointer(T)).*;
if (native_endian != endian) std.mem.byteSwapAllFields(T, &res);
return res;
},
.@"packed" => {
return @bitCast(try peekInt(r, info.backing_integer.?, endian));
},
},
else => @compileError("not a struct"),
}
}