implement CacheEntry deinit to clean up code a bit

This commit is contained in:
Emil Lerch 2026-01-06 09:12:27 -08:00
parent 95ce25919f
commit b466acb70a
Signed by: lobo
GPG key ID: A7B62D657EF764F8

19
src/cache/Cache.zig vendored
View file

@ -49,8 +49,7 @@ pub fn get(self: *Cache, key: []const u8) ?[]const u8 {
// Check L2 (disk)
const cached = self.loadFromFile(key) catch return null;
defer self.allocator.free(cached.key);
defer self.allocator.free(cached.value);
defer cached.deinit(self.allocator);
// L2 exists - promote to L1
self.lru.put(key, cached.value, cached.expires) catch return null;
@ -86,6 +85,11 @@ const CacheEntry = struct {
key: []const u8,
value: []const u8,
expires: i64,
pub fn deinit(self: CacheEntry, allocator: std.mem.Allocator) void {
allocator.free(self.key);
allocator.free(self.value);
}
};
/// Loads cached value from file (path calculated by the key). An error will be thrown
@ -113,7 +117,7 @@ fn loadFromFilePath(self: *Cache, file_path: []const u8) !CacheEntry {
const reader = &file_reader.interface;
const cached = try deserialize(self.allocator, reader);
errdefer self.allocator.free(cached.value);
errdefer cached.deinit(self.allocator);
// Check if expired
const now = std.time.milliTimestamp();
@ -179,8 +183,7 @@ fn loadFromDir(self: *Cache) !void {
defer self.allocator.free(file_path);
const cached = self.loadFromFilePath(file_path) catch continue;
defer self.allocator.free(cached.key);
defer self.allocator.free(cached.value);
defer cached.deinit(self.allocator);
// Populate L1 cache from L2
self.lru.put(cached.key, cached.value, cached.expires) catch continue;
@ -218,8 +221,7 @@ test "serialize and deserialize" {
var fixed_reader = std.Io.Reader.fixed(serialized);
const cached = try deserialize(allocator, &fixed_reader);
defer allocator.free(cached.key);
defer allocator.free(cached.value);
defer cached.deinit(allocator);
try std.testing.expectEqualStrings(key, cached.key);
try std.testing.expectEqualStrings(value, cached.value);
@ -234,8 +236,7 @@ test "deserialize handles integer expires" {
var fixed_reader = std.Io.Reader.fixed(json);
const cached = try deserialize(allocator, &fixed_reader);
defer allocator.free(cached.key);
defer allocator.free(cached.value);
defer cached.deinit(allocator);
try std.testing.expectEqualStrings("k", cached.key);
try std.testing.expectEqualStrings("v", cached.value);