-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path02_ttl_entries.zig
59 lines (46 loc) · 2.16 KB
/
02_ttl_entries.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const std = @import("std");
const Cache = @import("zigache").Cache;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var cache: Cache([]const u8, []const u8, .{
.ttl_enabled = true, // Enable TTL functionality
}) = try .init(allocator, .{
.cache_size = 10,
.policy = .SIEVE,
});
defer cache.deinit();
// Shows basic TTL functionality
try basicTTLUsage(&cache);
// Shows how TTL interacts with cache operations
try ttlInteractions(&cache);
}
fn basicTTLUsage(cache: anytype) !void {
std.debug.print("\n--- Basic TTL Usage ---\n", .{});
// Set an item with a 1 second TTL
try cache.putWithTTL("short_lived", "i'll be gone soon", 1000);
std.debug.print("short_lived (immediate): {?s}\n", .{cache.get("short_lived")});
// Set an item with a longer TTL
try cache.putWithTTL("long_lived", "i'll stick around", 10000);
std.debug.print("long_lived (immediate): {?s}\n", .{cache.get("long_lived")});
// After 1 second, short_lived should be gone, but long_lived should remain
std.time.sleep(1 * std.time.ns_per_s);
std.debug.print("short_lived (after 1s): {?s}\n", .{cache.get("short_lived")});
std.debug.print("long_lived (after 1s): {?s}\n", .{cache.get("long_lived")});
}
fn ttlInteractions(cache: anytype) !void {
std.debug.print("\n--- TTL Interactions ---\n", .{});
// Set an item with a 3 second TTL
try cache.putWithTTL("interactive", "original value", 3000);
std.debug.print("interactive (immediate): {?s}\n", .{cache.get("interactive")});
// After 1 second, update the value and TTL
std.time.sleep(1 * std.time.ns_per_s);
try cache.putWithTTL("interactive", "updated value", 5000);
// After 2 more seconds, the item should still be present due to the TTL update
std.time.sleep(2 * std.time.ns_per_s);
std.debug.print("interactive (after 3s): {?s}\n", .{cache.get("interactive")});
// After 3 more seconds, the item should be gone
std.time.sleep(3 * std.time.ns_per_s);
std.debug.print("interactive (after 6s): {?s}\n", .{cache.get("interactive")});
}