wttr/src/cache/cache.zig

43 lines
1.3 KiB
Zig

const std = @import("std");
const LRU = @import("lru.zig").LRU;
pub const Cache = struct {
allocator: std.mem.Allocator,
lru: LRU,
cache_dir: []const u8,
file_threshold: usize,
pub const Config = struct {
max_entries: usize = 10_000,
file_threshold: usize = 1024,
cache_dir: []const u8,
};
pub fn init(allocator: std.mem.Allocator, config: Config) !Cache {
std.fs.makeDirAbsolute(config.cache_dir) catch |err| {
if (err != error.PathAlreadyExists) return err;
};
return Cache{
.allocator = allocator,
.lru = try LRU.init(allocator, config.max_entries),
.cache_dir = try allocator.dupe(u8, config.cache_dir),
.file_threshold = config.file_threshold,
};
}
pub fn get(self: *Cache, key: []const u8) ?[]const u8 {
return self.lru.get(key);
}
pub fn put(self: *Cache, key: []const u8, value: []const u8, ttl_seconds: u64) !void {
const now = std.time.milliTimestamp();
const expires = now + @as(i64, @intCast(ttl_seconds * 1000));
try self.lru.put(key, value, expires);
}
pub fn deinit(self: *Cache) void {
self.lru.deinit();
self.allocator.free(self.cache_dir);
}
};