Make header always a packed struct

This lets us easily use the same writeStructe(header) pattern to write the header for each message type.
This commit is contained in:
2025-04-03 00:15:30 -04:00
parent 46ac234c80
commit 055539af7d

View File

@@ -19,19 +19,26 @@ const SaprusConnectionOptions = packed struct {
};
const SaprusMessage = union(SaprusPacketType) {
relay: struct {
dest: [4]u8,
const Relay = struct {
header: packed struct {
dest: @Vector(4, u8),
},
payload: []u8,
},
};
const Connection = struct {
header: packed struct {
src_port: u16,
dest_port: u16,
seq_num: u32 = 0,
msg_id: u32 = 0,
reserved: u8 = 0,
options: SaprusConnectionOptions = .{},
},
payload: []u8,
};
relay: Relay,
file_transfer: void, // unimplemented
connection: packed struct {
src_port: u16,
dest_port: u16,
seq_num: u32 = 0,
msg_id: u32 = 0,
reserved: u8 = 0,
options: SaprusConnectionOptions = .{},
},
connection: Connection,
const Self = @This();
@@ -42,13 +49,15 @@ const SaprusMessage = union(SaprusPacketType) {
switch (s) {
.relay => |r| {
try w.writeAll(&r.dest);
try w.writeStruct(r.header);
try w.writeInt(u16, @intCast(r.payload.len), .big);
try base64.encodeWriter(w, r.payload);
},
.file_transfer => unreachable,
.connection => |c| {
try w.writeStruct(c);
try w.writeStruct(c.header);
try w.writeInt(u16, @intCast(c.payload.len), .big);
try base64.encodeWriter(w, c.payload);
},
}
@@ -67,7 +76,7 @@ pub fn main() !void {
const msg = SaprusMessage{
.relay = .{
.dest = .{ 255, 255, 255, 255 },
.header = .{ .dest = .{ 255, 255, 255, 255 } },
.payload = @ptrCast(@constCast("Hello darkness my old friend")),
},
};