地圖 (Jido) is a lightweight Unix TUI file explorer designed for speed and simplicity.
1const std = @import("std");
2
3pub fn CircularStack(comptime T: type, comptime capacity: usize) type {
4 return struct {
5 const Self = @This();
6
7 head: usize = 0,
8 count: usize = 0,
9 buf: [capacity]T = undefined,
10
11 pub fn init() Self {
12 return Self{};
13 }
14
15 pub fn reset(self: *Self) void {
16 self.head = 0;
17 self.count = 0;
18 }
19
20 pub fn push(self: *Self, v: T) ?T {
21 const prev_elem = if (self.count == capacity) self.buf[self.head] else null;
22
23 self.buf[self.head] = v;
24 self.head = (self.head + 1) % capacity;
25 if (self.count != capacity) self.count += 1;
26
27 return prev_elem;
28 }
29
30 pub fn pop(self: *Self) ?T {
31 if (self.count == 0) return null;
32
33 self.head = if (self.head == 0) capacity - 1 else self.head - 1;
34 const value = self.buf[self.head];
35 self.count -= 1;
36 return value;
37 }
38 };
39}
40
41const testing = std.testing;
42
43test "CircularStack: push and pop basic operations" {
44 var stack = CircularStack(u32, 5).init();
45
46 _ = stack.push(1);
47 _ = stack.push(2);
48 _ = stack.push(3);
49
50 try testing.expectEqual(@as(?u32, 3), stack.pop());
51 try testing.expectEqual(@as(?u32, 2), stack.pop());
52 try testing.expectEqual(@as(?u32, 1), stack.pop());
53 try testing.expectEqual(@as(?u32, null), stack.pop());
54}
55
56test "CircularStack: wraparound behavior at capacity" {
57 var stack = CircularStack(u32, 3).init();
58
59 _ = stack.push(1);
60 _ = stack.push(2);
61 _ = stack.push(3);
62
63 const evicted = stack.push(4);
64 try testing.expectEqual(@as(?u32, 1), evicted);
65
66 try testing.expectEqual(@as(?u32, 4), stack.pop());
67 try testing.expectEqual(@as(?u32, 3), stack.pop());
68 try testing.expectEqual(@as(?u32, 2), stack.pop());
69}
70
71test "CircularStack: reset clears all entries" {
72 var stack = CircularStack(u32, 5).init();
73
74 _ = stack.push(1);
75 _ = stack.push(2);
76 _ = stack.push(3);
77
78 stack.reset();
79
80 try testing.expectEqual(@as(?u32, null), stack.pop());
81 try testing.expectEqual(@as(usize, 0), stack.count);
82}