| ... | ... | @@ -4,6 +4,7 @@ |
| 4 | 4 | //! if full or empty can be distinguised by looking at the different between the read and write |
| 5 | 5 | //! indices without adding an extra boolean flag or having to reserve a slot in the buffer. |
| 6 | 6 | |
| 7 | const Allocator = @import("std").mem.Allocator; |
| 7 | 8 | const assert = @import("std").debug.assert; |
| 8 | 9 | |
| 9 | 10 | const RingBuffer = @This(); |
| ... | ... | @@ -12,6 +13,22 @@ data: []u8, |
| 12 | 13 | read_index: usize, |
| 13 | 14 | write_index: usize, |
| 14 | 15 | |
| 16 | /// Allocate a new `RingBuffer` |
| 17 | pub fn init(allocator: Allocator, capacity: usize) Allocator.Error!RingBuffer { |
| 18 | const bytes = try allocator.alloc(u8, capacity); |
| 19 | return RingBuffer{ |
| 20 | .data = bytes, |
| 21 | .write_index = 0, |
| 22 | .read_index = 0, |
| 23 | }; |
| 24 | } |
| 25 | |
| 26 | /// Free a `RingBuffer` |
| 27 | pub fn deinit(self: *RingBuffer, allocator: Allocator) void { |
| 28 | allocator.free(self.data); |
| 29 | self.* = undefined; |
| 30 | } |
| 31 | |
| 15 | 32 | /// Returns `index` modulo the length of the backing slice. |
| 16 | 33 | pub fn mask(self: RingBuffer, index: usize) usize { |
| 17 | 34 | return index % self.data.len; |
| ... | ... | @@ -70,7 +87,7 @@ pub fn isFull(self: RingBuffer) bool { |
| 70 | 87 | |
| 71 | 88 | /// Returns the length |
| 72 | 89 | pub fn len(self: RingBuffer) usize { |
| 73 | | const adjusted_write_index = self.write_index + @boolToInt(self.write_index < self.read_index) * 2 * self.data.len; |
| 90 | const adjusted_write_index = self.write_index + @as(usize, @boolToInt(self.write_index < self.read_index)) * 2 * self.data.len; |
| 74 | 91 | return adjusted_write_index - self.read_index; |
| 75 | 92 | } |
| 76 | 93 | |