const Message = @import("message_parser.zig").Message; const std = @import("std"); pub const ClientState = struct { id: usize, connect: Message.Connect, /// Messages that this client is trying to send. send_queue: std.Io.Queue(Message), send_queue_buffer: [1024]Message = undefined, /// Messages that this client should receive. recv_queue: std.Io.Queue(Message), recv_queue_buffer: [1024]Message = undefined, /// Mapping of the subjects to the IDs. subscription_ids: std.StringHashMapUnmanaged([]const u8) = .empty, pub fn init(id: usize, connect: Message.Connect) ClientState { var res: ClientState = .{ .id = id, .connect = connect, .send_queue = undefined, .recv_queue = undefined, }; res.send_queue = .init(&res.send_queue_buffer); res.recv_queue = .init(&res.recv_queue_buffer); return res; } pub fn deinit(self: *ClientState, alloc: std.mem.Allocator) void { self.subscription_ids.clearAndFree(alloc); } pub fn subscribe(self: *ClientState, gpa: std.mem.Allocator, sub: Message.Sub) !void { self.subscription_ids.lockPointers(); defer self.subscription_ids.unlockPointers(); try self.subscription_ids.putNoClobber(gpa, sub.subject, sub.sid); } pub fn unsubscribe(self: *ClientState, gpa: std.mem.Allocator, sid: []const u8) void { _ = gpa; self.subscription_ids.lockPointers(); defer self.subscription_ids.unlockPointers(); var iter = self.subscription_ids.iterator(); while (iter.next()) |entry| { if (std.mem.eql(u8, sid, entry.value_ptr.*)) { self.subscription_ids.swapRemove(entry.value_ptr.*); break; } } else unreachable; // Assert that the SID is in the subscriptions. } };