From 6fe2b4077896218083f778e926217f596a58a550 Mon Sep 17 00:00:00 2001 From: dweiller <4678790+dweiller@users.noreply.github.com> Date: Sun, 10 Mar 2024 18:17:23 +1100 Subject: [PATCH] std.RingBuffer: use sliceAt/sliceFirst in read*AssumeLength --- lib/std/RingBuffer.zig | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/lib/std/RingBuffer.zig b/lib/std/RingBuffer.zig index f47895ae5b..5bdfb3e070 100644 --- a/lib/std/RingBuffer.zig +++ b/lib/std/RingBuffer.zig @@ -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