From 89c63a34c166e9b2155e7ccfd11ed45c1a57b08f Mon Sep 17 00:00:00 2001 From: Jacob Jonsson Date: Sun, 4 Jan 2026 23:52:42 +0100 Subject: [PATCH] chore(bot.zig): store references to messages in bot --- src/bot.zig | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/src/bot.zig b/src/bot.zig index c35219f..658e6b6 100644 --- a/src/bot.zig +++ b/src/bot.zig @@ -132,7 +132,7 @@ pub const Message = struct { author: []const u8, content: []const u8, - pub fn new_owned(allocator: std.mem.Allocator, timestamp: i64, author: []const u8, targets: []const u8, content: []const u8) Error!Message { + pub fn init_owned(allocator: std.mem.Allocator, timestamp: i64, author: []const u8, targets: []const u8, content: []const u8) Error!Message { return .{ .timestamp = timestamp, .targets = try allocator.dupe(u8, targets), @@ -141,7 +141,7 @@ pub const Message = struct { }; } - pub fn deinit(self: Message, allocator: std.mem.Allocator) void { + pub fn deinit(self: *const Message, allocator: std.mem.Allocator) void { allocator.free(self.author); allocator.free(self.content); allocator.free(self.targets); @@ -149,7 +149,7 @@ pub const Message = struct { }; pub const Bot = struct { - backlog: [1024]?Message, + backlog: [1024]?*const Message, sent_messages: std.ArrayList([]u8), top: usize, bottom: usize, @@ -247,7 +247,7 @@ pub const Bot = struct { } } - pub fn hear(self: *Bot, msg: Message) void { + pub fn hear(self: *Bot, msg: *const Message) void { self.backlog[self.top] = msg; self.top = (self.top + 1) % self.backlog.len; if (self.top == self.bottom) { @@ -274,7 +274,7 @@ pub const Bot = struct { return (idx - 1) % self.backlog.len; } - fn previous_message_by_author(self: *Bot, author: []const u8, targets: []const u8) ?Message { + fn previous_message_by_author(self: *Bot, author: []const u8, targets: []const u8) ?*const Message { var idx = self.previous_idx(self.top); while (true) : (idx = self.previous_idx(idx)) { if (self.backlog[idx] == null) { @@ -297,14 +297,15 @@ test "hear_wraps" { var bot = try Bot.init(std.testing.allocator); defer bot.deinit(); - const testMessage = Message{ - .author = "Jassob", - .timestamp = 12345, - .content = "All your codebase are belong to us.\n", - }; - for (0..1025) |_| { - bot.hear(testMessage); + const testMessage = try Message.init_owned( + std.testing.allocator, + 12345, + "jassob", + "#test", + "All your codebase are belong to us.\n", + ); + bot.hear(&testMessage); } try std.testing.expect(bot.top == 1); @@ -324,7 +325,14 @@ test "execute_substitution" { defer bot.deinit(); // hear original message with typo - bot.hear(Message{ .timestamp = 1234, .author = "jassob", .content = "What" }); + const msg = try Message.init_owned( + std.testing.allocator, + 1234, + "jassob", + "#test", + "What", + ); + bot.hear(&msg); // execute substitution const cmd = Command{