zdt-prov/src/cache.zig
2026-01-20 19:03:14 -03:00

63 lines
1.9 KiB
Zig

const std = @import("std");
const Allocator = std.heap.ArenaAllocator;
const parser = @import("parser.zig");
const icons = @import("svg/icons.zig");
pub const TemplateCache = struct {
arena: Allocator,
cache: std.StringHashMapUnmanaged([]parser.Node),
default_path: ?[]const u8 = "templates",
icons: ?icons.SvgIcon =null,
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 initIcons(self: *TemplateCache) !void {
self.icons = icons.SvgIcon.init(self.allocator()) catch null;
}
pub fn clear(self: *TemplateCache) void {
self.deinit();
self.cache = .{};
}
};