Function writeStruct [src]

The function is inline to avoid the dead code in case endian is comptime-known and matches host endianness.

Prototype

pub inline fn writeStruct(w: *Writer, value: anytype, endian: std.builtin.Endian) Error!void

Parameters

w: *Writerendian: std.builtin.Endian

Possible Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

Example

test writeStruct { var buffer: [16]u8 = undefined; const S = extern struct { a: u64, b: u32, c: u32 }; const s: S = .{ .a = 1, .b = 2, .c = 3 }; { var w: Writer = .fixed(&buffer); try w.writeStruct(s, .little); try testing.expectEqualSlices(u8, &.{ 1, 0, 0, 0, 0, 0, 0, 0, // 2, 0, 0, 0, // 3, 0, 0, 0, // }, &buffer); } { var w: Writer = .fixed(&buffer); try w.writeStruct(s, .big); try testing.expectEqualSlices(u8, &.{ 0, 0, 0, 0, 0, 0, 0, 1, // 0, 0, 0, 2, // 0, 0, 0, 3, // }, &buffer); } }

Source

pub inline fn writeStruct(w: *Writer, value: anytype, endian: std.builtin.Endian) Error!void { switch (@typeInfo(@TypeOf(value))) { .@"struct" => |info| switch (info.layout) { .auto => @compileError("ill-defined memory layout"), .@"extern" => { if (native_endian == endian) { return w.writeAll(@ptrCast((&value)[0..1])); } else { var copy = value; std.mem.byteSwapAllFields(@TypeOf(value), ©); return w.writeAll(@ptrCast((©)[0..1])); } }, .@"packed" => { return writeInt(w, info.backing_integer.?, @bitCast(value), endian); }, }, else => @compileError("not a struct"), } }