std.RingBuffer: use sliceAt/sliceFirst in read*AssumeLength

This commit is contained in:
dweiller 2024-03-10 18:17:23 +11:00
parent d942096a44
commit 6fe2b40778

View File

@ -150,12 +150,8 @@ pub fn readFirst(self: *RingBuffer, dest: []u8, length: usize) Error!void {
/// Uses memcpy and so `dest` must not overlap ring buffer data.
pub fn readFirstAssumeLength(self: *RingBuffer, dest: []u8, length: usize) void {
assert(length <= self.len() and length <= dest.len);
const data_start = self.mask(self.read_index);
const part1_data_end = @min(self.data.len, data_start + length);
const part1_len = part1_data_end - data_start;
const part2_len = length - part1_len;
@memcpy(dest[0..part1_len], self.data[data_start..part1_data_end]);
@memcpy(dest[part1_len..length], self.data[0..part2_len]);
const slice = self.sliceAt(self.read_index, length);
slice.copyTo(dest);
self.read_index = self.mask2(self.read_index + length);
}
@ -174,13 +170,12 @@ pub fn readLast(self: *RingBuffer, dest: []u8, length: usize) Error!void {
/// Reduces write index by `length`.
pub fn readLastAssumeLength(self: *RingBuffer, dest: []u8, length: usize) void {
assert(length <= self.len() and length <= dest.len);
const data_start = self.mask(self.write_index + self.data.len - length);
const part1_data_end = @min(self.data.len, data_start + length);
const part1_len = part1_data_end - data_start;
const part2_len = length - part1_len;
@memcpy(dest[0..part1_len], self.data[data_start..part1_data_end]);
@memcpy(dest[part1_len..length], self.data[0..part2_len]);
self.write_index = if (self.write_index >= self.data.len) self.write_index - length else data_start;
const slice = self.sliceLast(length);
slice.copyTo(dest);
self.write_index = if (self.write_index >= self.data.len)
self.write_index - length
else
self.mask(self.write_index + self.data.len - length);
}
/// Returns `true` if the ring buffer is empty and `false` otherwise.
@ -206,6 +201,12 @@ pub fn len(self: RingBuffer) usize {
pub const Slice = struct {
first: []u8,
second: []u8,
/// Copy data from `self` into `dest`
pub fn copyTo(self: Slice, dest: []u8) void {
@memcpy(dest[0..self.first.len], self.first);
@memcpy(dest[self.first.len..][0..self.second.len], self.second);
}
};
/// Returns a `Slice` for the region of the ring buffer starting at