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