jmatth11/rb.zig
A simple ring buffer in zig
Simple ring buffer written in zig.
Thread safe and provides a read function that gets notified when ring buffer is full.
zig fetch --save "git+https://github.com/jmatth11/rb.zig#main"
Place this in your build.zig
.
const rb = b.dependency("rb_zig", .{
.target = target,
.optimize = optimize,
});
// the executable from your call to b.addExecutable(...)
exe.root_module.addImport("rb", rb.module("rb_zig"));
const std = @import("std");
const rb = @import("rb");
// create ring buffer type with given capacity and type
const RingBuffer = rb.RingBuffer(50, u8);
// initialize the ring buffer
const buffer: RingBuffer = .init();
fn write(buf: []u8) !void {
for (buf) |ch| {
// write to the ring buffer
try buffer.write(ch, true);
}
}
fn read() !void {
// read from the ring buffer when either it's full or the time has expired.
// Use read_buffer for an allocation-free version.
const read_opt = try buffer.read(std.heap.smp_allocator, std.time.ns_per_s);
if (read_opt) |read_buf| {
// free allocated array
defer std.heap.smp_allocator.free(read_buf);
for (read_buf) |read_ch| {
// operate on data.
}
}
}