| 1 | const std = @import("std"); |
| 2 | const string = []const u8; |
| 3 | const extras = @import("./lib.zig"); |
| 4 | |
| 5 | pub fn RingBuffer(comptime T: type, comptime capacity: usize) type { |
| 6 | return struct { |
| 7 | items: [capacity]T, |
| 8 | len: usize, |
| 9 | comptime capacity: usize = capacity, |
| 10 | |
| 11 | const Self = @This(); |
| 12 | |
| 13 | pub const empty: Self = .{ |
| 14 | .items = undefined, |
| 15 | .len = 0, |
| 16 | }; |
| 17 | |
| 18 | pub fn append(self: *Self, new_item: T) void { |
| 19 | if (self.len == self.capacity) { |
| 20 | for (1..self.len) |i| self.items[i - 1] = self.items[i]; |
| 21 | self.len -= 1; |
| 22 | } |
| 23 | self.items[self.len] = new_item; |
| 24 | self.len += 1; |
| 25 | } |
| 26 | |
| 27 | pub fn slice(self: *Self) []T { |
| 28 | return self.items[0..self.len]; |
| 29 | } |
| 30 | |
| 31 | pub fn rest(self: *Self) []T { |
| 32 | return self.items[self.len..]; |
| 33 | } |
| 34 | }; |
| 35 | } |
| 36 | |
| 37 | test { |
| 38 | std.testing.refAllDecls(RingBuffer(u8, 16)); |
| 39 | } |