Simplified a ton of things and cleaned up ownership

This commit is contained in:
2025-12-31 03:11:42 +00:00
parent 0f138e5984
commit a781876038
3 changed files with 89 additions and 46 deletions

View File

@@ -7,6 +7,8 @@ pub const ClientState = struct {
/// Messages that this client should receive.
recv_queue: std.Io.Queue(Message) = undefined,
recv_queue_buffer: [1024]Message = undefined,
// Used to take ownership of values as they are put in the queue.
recv_alloc: std.mem.Allocator,
from_client: *std.Io.Reader,
to_client: *std.Io.Writer,
@@ -15,11 +17,13 @@ pub const ClientState = struct {
pub fn init(
connect: Message.AllocatedConnect,
alloc: std.mem.Allocator,
in: *std.Io.Reader,
out: *std.Io.Writer,
) !ClientState {
var res: ClientState = .{
.connect = connect,
.recv_alloc = alloc,
.from_client = in,
.to_client = out,
};
@@ -49,6 +53,7 @@ pub const ClientState = struct {
writeInfo(self.to_client, info) catch break;
},
.msg => |m| {
defer m.deinit(self.recv_alloc);
writeMsg(self.to_client, m) catch break;
},
else => {
@@ -68,8 +73,16 @@ pub const ClientState = struct {
}
/// Return true if the value was put in the clients buffer to process, else false.
pub fn send(self: *ClientState, io: std.Io, msg: Message) (std.Io.Cancelable || std.Io.QueueClosedError)!void {
try self.recv_queue.putOne(io, msg);
pub fn send(self: *ClientState, io: std.Io, msg: Message) !void {
// Client needs to own msg that is put in its queue
switch (msg) {
.msg => |m| {
try self.recv_queue.putOne(io, .{ .msg = try m.dupe(self.recv_alloc) });
},
else => {
try self.recv_queue.putOne(io, msg);
},
}
}
pub fn next(self: *ClientState, allocator: std.mem.Allocator) !Message {