This ring buffer stores read and write indices while being able to utilise the full backing slice by incrementing the indices modulo twice the slice’s length and reducing indices modulo the slice’s length on slice access. This means that whether the ring buffer is full or empty can be distinguished by looking at the difference between the read and write indices without adding an extra boolean flag or having to reserve a slot in the buffer.
This ring buffer has not been implemented with thread safety in mind, and therefore should not be assumed to be suitable for use cases involving separate reader and writer threads.
Functions
fn deinit(self: *RingBuffer, allocator: Allocator) void
Free the data backing a
RingBuffer
; must be passed the sameAllocator
as `i…Free the data backing a
RingBuffer
; must be passed the sameAllocator
asinit()
.fn init(allocator: Allocator, capacity: usize) Allocator.Error!RingBuffer
Allocate a new
RingBuffer
;deinit()
should be called to free the buffer.fn mask2(self: RingBuffer, index: usize) usize
Returns
index
modulo twice the length of the backing slice.fn read(self: *RingBuffer) ?u8
Consume a byte from the ring buffer and return it. Returns
null
if the ring b…Consume a byte from the ring buffer and return it. Returns
null
if the ring buffer is empty.fn readAssumeLength(self: *RingBuffer) u8
Consume a byte from the ring buffer and return it; asserts that the buffer is n…
Consume a byte from the ring buffer and return it; asserts that the buffer is not empty.
fn write(self: *RingBuffer, byte: u8) Error!void
Write
byte
into the ring buffer. Returnserror.Full
if the ring buffer is f…Write
byte
into the ring buffer. Returnserror.Full
if the ring buffer is full.fn writeAssumeCapacity(self: *RingBuffer, byte: u8) void
Write
byte
into the ring buffer. If the ring buffer is full, the oldest byte …Write
byte
into the ring buffer. If the ring buffer is full, the oldest byte is overwritten.fn writeSlice(self: *RingBuffer, bytes: []const u8) Error!void
Write
bytes
into the ring buffer. Returnserror.Full
if the ring buffer doe…Write
bytes
into the ring buffer. Returnserror.Full
if the ring buffer does not have enough space, without writing any data.fn writeSliceAssumeCapacity(self: *RingBuffer, bytes: []const u8) void
Write
bytes
into the ring buffer. If there is not enough space, older bytes w…Write
bytes
into the ring buffer. If there is not enough space, older bytes will be overwritten.