Function takeStruct [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:
takeStructPointer
peekStruct
Prototype
pub inline fn takeStruct(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 takeStruct {
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.takeStruct(S, .big));
try testing.expectError(error.EndOfStream, r.takeStruct(S, .little));
}
Source
pub inline fn takeStruct(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.takeStructPointer(T)).*;
if (native_endian != endian) std.mem.byteSwapAllFields(T, &res);
return res;
},
.@"packed" => {
return @bitCast(try takeInt(r, info.backing_integer.?, endian));
},
},
else => @compileError("not a struct"),
}
}