|
1 | | -//! This ring buffer stores read and write indices while being able to utilise the full |
2 | | -//! backing slice by incrementing the indices modulo twice the slice's length and reducing |
3 | | -//! indices modulo the slice's length on slice access. This means that whether the ring buffer |
4 | | -//! if full or empty can be distinguised by looking at the different between the read and write |
5 | | -//! indices without adding an extra boolean flag or having to reserve a slot in the buffer. |
| 1 | +//! This ring buffer stores read and write indices while being able to utilise |
| 2 | +//! the full backing slice by incrementing the indices modulo twice the slice's |
| 3 | +//! length and reducing indices modulo the slice's length on slice access. This |
| 4 | +//! means that whether the ring buffer if full or empty can be distinguised by |
| 5 | +//! looking at the different between the read and write indices without adding |
| 6 | +//! an extra boolean flag or having to reserve a slot in the buffer. |
| 7 | +//! |
| 8 | +//! This ring buffer has not been implemented with thread safety in mind, and |
| 9 | +//! therefore should not be assumed to be suitable for use cases involving |
| 10 | +//! separate reader and writer threads. |
6 | 11 |
|
7 | 12 | const Allocator = @import("std").mem.Allocator; |
8 | 13 | const assert = @import("std").debug.assert; |
@@ -72,6 +77,13 @@ pub fn writeSliceAssumeCapacity(self: *RingBuffer, bytes: []const u8) void { |
72 | 77 | /// ring buffer is empty. |
73 | 78 | pub fn read(self: *RingBuffer) ?u8 { |
74 | 79 | if (self.isEmpty()) return null; |
| 80 | + return self.readAssumeLength(); |
| 81 | +} |
| 82 | + |
| 83 | +/// Consume a byte from the ring buffer and return it; asserts that the buffer |
| 84 | +/// is not empty. |
| 85 | +pub fn readAssumeLength(self: *RingBuffer) u8 { |
| 86 | + assert(!self.isEmpty()); |
75 | 87 | const byte = self.data[self.mask(self.read_index)]; |
76 | 88 | self.read_index = self.mask2(self.read_index + 1); |
77 | 89 | return byte; |
|
0 commit comments