update: add cache

This commit is contained in:
Lucas F. 2026-01-11 20:39:04 -03:00
parent cba0c8d749
commit 3c3bd6d05f
2 changed files with 106 additions and 19 deletions

57
src/cache.zig Normal file
View file

@ -0,0 +1,57 @@
const std = @import("std");
const Allocator = std.heap.ArenaAllocator;
const parser = @import("parser.zig");
pub const TemplateCache = struct {
arena: Allocator,
cache: std.StringHashMapUnmanaged([]parser.Node),
pub fn init(child_allocator: std.mem.Allocator) TemplateCache {
const arena = std.heap.ArenaAllocator.init(child_allocator);
return .{
.arena = arena,
.cache = .{},
};
}
pub fn deinit(self: *TemplateCache) void {
self.arena.deinit();
}
pub fn allocator(self: *TemplateCache) std.mem.Allocator {
return self.arena.allocator();
}
pub fn get(self: *const TemplateCache, key: []const u8) ?[]parser.Node {
return self.cache.get(key);
}
pub fn add(self: *TemplateCache, key: []const u8, nodes: []parser.Node) !void {
// const key_copy = try self.arena.dupe(u8, key);
// errdefer self.arena.free(key_copy);
// try self.cache.put(self.arena, key, nodes);
const gop = try self.cache.getOrPut(self.allocator(), key);
if (!gop.found_existing) {
gop.key_ptr.* = try self.allocator().dupe(u8, key);
gop.value_ptr.* = nodes;
}
gop.value_ptr.* = nodes;
}
pub fn invalidate(self: *TemplateCache, key: []const u8) void {
if (self.cache.getEntry(key)) |entry| {
self.arena.free(entry.key_ptr.*);
for (entry.value_ptr.*) |node| node.deinit(self.arena);
self.arena.free(entry.value_ptr.*);
_ = self.cache.remove(key);
}
}
pub fn clear(self: *TemplateCache) void {
self.deinit();
self.cache = .{};
}
};