chore(bot.zig): store references to messages in bot

This commit is contained in:
Jacob Jonsson 2026-01-04 23:52:42 +01:00
parent 9bebf066cf
commit 89c63a34c1
Signed by: Jassob
GPG key ID: 7E30B9B047F7202E

View file

@ -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{