This commit is contained in:
2025-12-02 19:53:03 -05:00
parent 41f4ee721b
commit aceb671ddc
4 changed files with 366 additions and 141 deletions

View File

@@ -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.
}
};