diff options
| author | Robby Zambito <contact@robbyzambito.me> | 2025-12-02 19:53:03 -0500 |
|---|---|---|
| committer | Robby Zambito <contact@robbyzambito.me> | 2025-12-02 19:53:03 -0500 |
| commit | aceb671ddc3e4ff3ce15c2e9814538e4f21d7d12 (patch) | |
| tree | b9624d8c3ffe569735d1374ec9ce42b68258a5ca /src/server/client.zig | |
| parent | 41f4ee721b138304294b185185dc6fc51549c5b9 (diff) | |
Diffstat (limited to 'src/server/client.zig')
| -rw-r--r-- | src/server/client.zig | 58 |
1 files changed, 46 insertions, 12 deletions
diff --git a/src/server/client.zig b/src/server/client.zig index bc02611..037a4fa 100644 --- a/src/server/client.zig +++ b/src/server/client.zig @@ -1,17 +1,51 @@ const Message = @import("message_parser.zig").Message; const std = @import("std"); -const ClientState = struct { - id: u32, - /// Used to back `connect` strings. - string_buffer: [4096]u8, +pub const ClientState = struct { + id: usize, connect: Message.Connect, - send_queue: std.Io.Queue(Message) = blk: { - var send_queue_buffer: [1024]Message = undefined; - break :blk .init(&send_queue_buffer); - }, - recv_queue: std.Io.Queue(Message) = blk: { - var recv_queue_buffer: [1024]Message = undefined; - break :blk .init(&recv_queue_buffer); - }, + /// 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. + } }; |
