authorgravatar for 4678790+dweiller@users.noreply.github.comDominic <4678790+dweiller@users.noreply.github.com> 2023-01-31 12:54:05+11:00
committergravatar for 4678790+dweiller@users.noreply.github.comDominic <4678790+dweiller@users.noreply.github.com> 2023-02-20 09:09:06+11:00
log2d35c16ee7e4a8f69bbbe19b2a48cc03aed755c8
treecfc96af33cda96888b2c033dc5b6809c36cbcafd
parente92575d3d47b2701d0b93aa0f044caade57b71c8

std.compress.zstandard: add init/deinit for ring buffer, fix len()


1 files changed, 18 insertions(+), 1 deletions(-)

lib/std/compress/zstandard/RingBuffer.zig+18-1
......@@ -4,6 +4,7 @@
44//! if full or empty can be distinguised by looking at the different between the read and write
55//! indices without adding an extra boolean flag or having to reserve a slot in the buffer.
66
7const Allocator = @import("std").mem.Allocator;
78const assert = @import("std").debug.assert;
89
910const RingBuffer = @This();
......@@ -12,6 +13,22 @@ data: []u8,
1213read_index: usize,
1314write_index: usize,
1415
16/// Allocate a new `RingBuffer`
17pub 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`
27pub fn deinit(self: *RingBuffer, allocator: Allocator) void {
28 allocator.free(self.data);
29 self.* = undefined;
30}
31
1532/// Returns `index` modulo the length of the backing slice.
1633pub fn mask(self: RingBuffer, index: usize) usize {
1734 return index % self.data.len;
......@@ -70,7 +87,7 @@ pub fn isFull(self: RingBuffer) bool {
7087
7188/// Returns the length
7289pub 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;
7491 return adjusted_write_index - self.read_index;
7592}
7693